• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Class/Sub Class

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 + "," );
sup.printVal();
}
}
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Kalpesh Pandya
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks ! This surely helped me out !
 
reply
    Bookmark Topic Watch Topic
  • New Topic