I just feel, that the problem with the above code is that the subclass redeclares the variable already declared by superclass. The Runtime switching happens fine, If we remove it.
Please correct me if i am wrong.
Thanks,
Gokul.
Code:
Working fine:
class A{
int i=30;
}
class B extends A{
int j;
}
class
Test extends B{
public static void main(
String args[]){
A a;
B b1 = new B();
b1.i = 10;
a=b1;
System.out.println(a.i);
B b2 = new B();
b2.i = 20;
a=b2;
System.out.println(a.i);
}
}
Not Working Fine:
class A{
int i=30;
}
class B extends A{
int i;
int j;
}
class Test extends B{
public static void main(String args[]){
A a;
B b1 = new B();
b1.i = 10;
a=b1;
System.out.println(a.i);
B b2 = new B();
b2.i = 20;
a=b2;
System.out.println(a.i);//at compile time=a.i and at runtime b.i
}
}
Thanks,
Gokul.