Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance

 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having an super class named Base :




Subclass named Sub:


I want to know when i invoke System.out.print(s.FOO);...The super class variable gets printed...when i invoke s.eat(); the sub class method gets invoked.......why does System.out.print(s.FOO); doesnot print subclass variable ???
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance methods are polymorphic; they are called according to the runtime type of the object, ie Sub.
Everything else, including static fields, is not polymorphic, and called according to the declared type of the class, ie Base, in both cases. Base b = new Sub(); means its declared type is Base and its runtime type is Sub.
 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Campbell Ritchie :

Thanks !!
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic