• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt about instance members and polymorphism  RSS feed

 
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
Sheriff
Posts: 23034
120
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: 11096
173
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...!
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!