This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: mock exam question need some help
 
Similar Threads
Use of constructor in abstract class?
Doubt on program output from overriding
Instance Variables
Question
need help