• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overridding Pls Explain this code

 
Ganesh Kannusamy
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then how do we access the instance variable of a sub class with th esuper class ref variable. Is it not possible?
 
Pinkal Patel
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No you can not Directly Used Sub class Instance variable throw the Super class variable.
 
S Thiyanesh
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic