File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overridding Pls  Explain this code" Watch "Overridding Pls  Explain this code" New topic

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 + "," );

ANS: (5, sub)

Iam clear about "sub" as ouput, but not clear how "5" comes as output

Thanks for your reply,

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

wood burning stoves
subject: Overridding Pls Explain this code
Similar Threads
Use of constructor in abstract class?
Class/Sub Class
Instance Variables
need help