class Super { int index = 5; public void printVal() { System.out.println( "Super" ); } } class Sub extends Super { int index = 2; public void printVal() { System.out.println( "Sub" ); } } public class Runner { public static void main( String argv[] ) { Super sup = new Sub(); System.out.print( sup.index + "," ); sup.printVal(); } }
ANS: (5, sub)
Iam clear about "sub" as ouput, but not clear how "5" comes as output
Thanks for your reply, Ganesh
Thanks,
Ganesh
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
posted
0
You are creating a Sub object but referring to it with a Super reference.
Instance variables are not overridden, they are hidden.
When an instance variable in a subclass has the same name as an instance variable in a superclass, then the instance variable is chosen in the class that is the reference type.
Siri Naray
Ranch Hand
Joined: May 19, 2006
Posts: 105
posted
0
then how do we access the instance variable of a sub class with th esuper class ref variable. Is it not possible?
If you worry you cannot work... If you work you need not worry
Pinkal Patel
Ranch Hand
Joined: Jun 16, 2006
Posts: 57
posted
0
No you can not Directly Used Sub class Instance variable throw the Super class variable.
Pinkal Patel<br />SCJP 1.5<br />Preparing for SCWCD
S Thiyanesh
Ranch Hand
Joined: Mar 19, 2006
Posts: 142
posted
0
Only overridden instance methods are bind to run time polymorphism. Others instance variables, static variables, static overridden (hidden) methods, and overloaded methods are all binded at compile time depending on the type of the reference variable and not on the object.
Finner Jones
Ranch Hand
Joined: Jun 12, 2006
Posts: 39
posted
0
then how do we access the instance variable of a sub class with th esuper class ref variable. Is it not possible?
You can use getter / setter access methods and override them in the subclasses.
The output is 2, Sub
Finner
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.