Sunday, July 22, 2007

Method Overriding versus Variable Shadowing in java

Method overriding is not like variable shadowing at all. Lets us have an example...

 class A {  
int i = 1;

int f() {
return i;
}
}

class B extends A {
int i = 2; // Shadows variable i in class A.

int f() {
return -i;
} // Overrides method f in class A.
}

public class Override_test {
public static void main(String args[]) {
B b = new B();
System.out.println(b.i); // Refers to B.i; prints 2.
System.out.println(b.f()); // Refers to B.f(); prints -2.
A a = (A) b; // Cast b to an instance of class A.
System.out.println(a.i); // Now refers to A.i; prints 1;
System.out.println(a.f()); // Still refers to B.f(); prints -2;
}
}



Another example of method overriding and variable shadowing

 class Parent {  
String classStr = "Parent";

void test() {
getClassName();
System.out.println(classStr);
}
void getClassName() {
System.out.println("Parent");
}
}

class Child extends Parent {
String classStr = "Child";

void test() {
super.test();
}
void getClassName() {
System.out.println("Child");
}
}

public class Main {
public static void main(String a[]) {
Child child = new Child();
child.test();
}
}


Output:
=======
Child
Parent

No comments: