This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why no Polymorphism for instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why no Polymorphism for instance variables" Watch "Why no Polymorphism for instance variables" New topic
Author

Why no Polymorphism for instance variables

Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
Why following code is printing B,10? Why not B,20?
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
Instance variable access is determined by the declared type, not the actual type. Polymorphism is only for instance methods.


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Naveed Ali
Ranch Hand

Joined: Aug 30, 2002
Posts: 41
Hi All!
This is my first post.
Ron, first what do you mean by actual & declared type.Second in this case (in my view) it should call method b.callme().So how it went to 'a'.
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
Hi Naveed:
A a = new B();
The declared type is on the left of variable a i.e. A in this case. So rest of the world (I mean program) will see that type of a is A. However, an object of type B is being refered by a. This is actual type of a. So when you call a method on A, the overridden version in the B will be invoked -- which is generally known as polymorphism.
 
Don't get me started about those stupid light bulbs.
 
subject: Why no Polymorphism for instance variables