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 Class/Sub Class 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 "Class/Sub Class" Watch "Class/Sub Class" New topic

Class/Sub Class

Kalpesh Pandya

Joined: Oct 07, 2000
Posts: 14
Following code prints answer as -> 5,Sub. I can understand sub but not 5, would anybody explain why?
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 + "," );
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Kalpesh,
The Java runtime resolves references to the actual class of the object when invoking methods but uses the declared class when grabbing fields.
In your code, <code>Super sub = new Sub()</code> the declared type of the object <code>sub</code> is <code>Super so <code>System.out.println(sub.index)</code> uses the index field defined in the Super class.
The actual type of the object <code>sub</code> is <code>Sub</code> so <code>sub.printVal()</code> uses the the <code>printVal()</code> defined in the <code>Sub</code> class.
Hope that helps.

Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Kalpesh Pandya

Joined: Oct 07, 2000
Posts: 14
Thanks ! This surely helped me out !
I agree. Here's the link:
subject: Class/Sub Class
Similar Threads
Use of constructor in abstract class?
Instance Variables
Basic Java Question
Overridding Pls Explain this code