GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overridding Pls  Explain this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overridding Pls  Explain this code" Watch "Overridding Pls  Explain this code" New topic
Author

Overridding Pls Explain this code

Ganesh Kannusamy
Ranch Hand

Joined: Sep 15, 2005
Posts: 35
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: 2367
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
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
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
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

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
 
GeeCON Prague 2014
 
subject: Overridding Pls Explain this code