• Post Reply Bookmark Topic Watch Topic
  • New Topic

Polymorphism  RSS feed

 
Vijay Narayanan
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is the following,
class A {
int i =0;
}
public class B extends A{
int i = 100;
public static void main(String[] args){
A a = new A(); System.out.println("A:i = " + a.i);
B b = new B(); System.out.println("B:i = " + b.i);
A c = new B(); System.out.println("Wanted i = " + c.i);
}
}
The output is :
A:i = 0
B:i = 100
Wanted i = 0
I feel that at runtime the JVM should have known that the object in variable c is actually a B object and should have printed the value "Wanted i = 100" and not what I got. Somehow Polymorphism is not working for instance variables, though if the same had happened with methods, the method is B would have been called.
Plz help...
 
Manish Hatwalne
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vijay Narayanan:
My question is the following,
I feel that at runtime the JVM should have known that the object in variable c is actually a B object and should have printed the value "Wanted i = 100" and not what I got. Somehow Polymorphism is not working for instance variables, though if the same had happened with methods, the method is B would have been called.
Plz help...

Well, variables are not virtual like methods and are not overriden, they do not have any polymorphic behaviour. The JLS is pretty clear on this one, this is just an example of shadowing.
HTH,
- Manish
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vijay
To expand on what Manish said:
In Java the value of a variable (and static methods) is determined at run time by the type of class referenced by the variable. In your example the variable c is declared to reference an A object.
Which method is invoked is determined at run time based on the type of the object that the variable references. In your example if instead of accessng the variable i you had invoked a method you wuold have gotten the version that was overriden in class B.
hope that helps clear it up for you
------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
[This message has been edited by Dave Vick (edited November 02, 2001).]
 
Hassan Naqvi
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this....http://www.javaranch.com/ubb/Forum24/HTML/012379.html
it may helps you
Regards,
Hassan.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!