Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt about instance members and polymorphism

 
kiran madhan
Ranch Hand
Posts: 30
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i did not understand this code in main() method

System.out.println(b.i) is not accessing -1  but accessing 99 from base class...!
What would be the reason...But it is accessing method properly...?


can somebody clear it..? please.
 
Henry Wong
author
Marshal
Pie
Posts: 22111
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kiran madhan wrote:
System.out.println(b.i) is not accessing -1  but accessing 99 from base class...!
What would be the reason...But it is accessing method properly...?


Well, simply, polymorphism does not apply to instance variables. The variable to access is determined at compile time, and the compiler uses the reference type to choose the variable to access.

Henry
 
kiran madhan
Ranch Hand
Posts: 30
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow...thanks Henry Wong for your valuable answer....thanks a lot
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi kiran madhan,

First of all, a warm welcome to CodeRanch!

kiran madhan wrote:System.out.println(b.i) is not accessing -1  but accessing 99 from base class...!
What would be the reason...But it is accessing method properly...?

Here are two very simple (and hopefully easy to remember) but very, very, very important rules (which you must know by heart):
  • Which instance variables you can access is determined at compile time based on the reference variable type.
  • Which instance methods you can call/invoke is determined at compile time based on the reference variable type. Which instance method is actually executed is decided at runtime based on the type of the actual object (= polymorphism).


  • Hope it helps!
    Kind regards,
    Roel
     
    kiran madhan
    Ranch Hand
    Posts: 30
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks a lot dear sir....Roel De Nijs...!
    It is the answer cleared everything...!
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic