permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes mock exam question need some help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "mock exam question need some help" Watch "mock exam question need some help" New topic

mock exam question need some help

aryan sanghvi

Joined: Jun 13, 2002
Posts: 21
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 + "," );
The above question is from:
ans: (5, super)
It is unclear to me that that method from subclass
is executed.But the value is sup.index as expected.
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
I'm sorry but if you try to run the code the output is not (5,super) but (5,sub)...
The statement Super sup = new Sub();
declares a reference variable of type Super referencing an object of runtime type Sub. Field accesses are resolved according to the declared type of the variable (i.e. Super) while methods are resolved according to the runtime type of the variable (i.e. Sub). Thus,
sup.index is resolved to the value of the member called index in the class Super.
Since method printVal() is overridden in Sub, sup.printVal() is resolved to the printVal() method in the class Sub.

[Blog] [Blogroll] [My Reviews] My Linked In
Don't get me started about those stupid light bulbs.
subject: mock exam question need some help
Similar Threads
Use of constructor in abstract class?
Doubt on program output from overriding
Instance Variables
need help