aspose file tools*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "mock exam question need some help" Watch "mock exam question need some help" New topic
Author

mock exam question need some help

aryan sanghvi
Greenhorn

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 + "," );
sup.printVal();
}
}
The above question is from:
MindQ_s_Sun_Certified_Java_Programmer_Practice_Test.htm
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
Sheriff

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.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
 
subject: mock exam question need some help