Forums Register Login

INSTANCE VARIABLES

+Pie Number of slices to send: Send
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);
}
}
+Pie Number of slices to send: Send
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).
+Pie Number of slices to send: Send
The reason is: Polymorphism applies only to methods and not to instance variables.
+Pie Number of slices to send: Send
The unlike override method, instance variable determined at compilation times not runtime.



a is declared of type A so a = 10 not 20
+Pie Number of slices to send: Send
 

Originally posted by Mahrez Marouani:
The reason is: Polymorphism applies only to non-static methods and not to instance variables.


[ November 18, 2008: Message edited by: Wouter Oet ]
+Pie Number of slices to send: Send
I want to know the reason of one doubt.

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?

Please help.

Thanks in advance.
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
Thanks Fabio. I got it. The explanation was good.
We must storm this mad man's lab and destroy his villanous bomb! Are you with me tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 682 times.
Similar Threads
[constructor]...
Private Field
pls clarify
explain
ObjectInput and OutputStreams
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 02:56:17.