Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt on program output from overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on program output from overriding" Watch "Doubt on program output from overriding" New topic
Author

Doubt on program output from overriding

R .sourav nayak
Ranch Hand

Joined: May 14, 2006
Posts: 67
Could some one tell me why the out put is 5, sub instead of 2 ,sub from the following program:

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();
}
}
thanks in advance
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
If there is an instance variable in the subclass with the same name as an instance variable in the superclass, then the reference type determines which variable is used not the runtime type of the object.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt on program output from overriding