can anyone tell me the following answer?give me detailed reson? class A { int x=10; } class B extends A { int x=20; } class Test { public static void main(String args[]) { A a=new B(); System.out.println(a.x); } }
The answer is :10 May be you are expecting it to print 20....Even if the object is of the sub classs type. The reason is because the base class reference variable CANNOT refer the members of the subclass(unless overridden).
When we extend class B by inheriting class A we also incorporate the variables. Now when are we redefining the variables then why the compiler is not giving any error? is not like defining same variable two times?
Yeah but, theres no overriden variables so you always access variables of your reference type and not of your object.
A a = new B(); // B extends A
Any access to "a.anyVariable" will reffer to the A class. Any access to "a.anyMethod" at compile time will reffer to the A class. But with methods the polymorphism get in action at runtime and if you have an overriden method in B, then in the runtime it will execute the B's method.
Got it?
To see that in action, declare an y variable in B class and try to access it with "a.y", you will get a "cannot find symbol" compile error, since the compiler will look for "y" in the "A" class (which is the reference type) [ November 18, 2008: Message edited by: Fabio Nascimento ]