aspose file tools*
The moose likes Beginning Java and the fly likes Polymorphism on data members Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polymorphism on data members" Watch "Polymorphism on data members" New topic
Author

Polymorphism on data members

Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
It seems that in Java Polymorphism is only for member functions. Data members' value do not get resolved to overridden value in actual object type.
So if a member function is using data member value, member function will be polymorphic but data member will NOT be polymorphic.
Is that by design in Java or a limition or my misunderstanding?
For example code will return 1 1 1 instead of 1 2 3

class Level1
{
int x = 1;
int returnX()
{
return this.x;
}
}

class Level2 extends Level1
{
int x = 2;

}
class Level3 extends Level2
{
int x = 3;

}
public class Level_Hier3
{
public static void main(String [] args)
{
Level1 obj1 = new Level1();
Level1 obj2 = new Level2();
Level1 obj3 = new Level3();
System.out.println(obj1.returnX()
+ " " + obj2.returnX()
+ " " + obj3.returnX());
}
}
Thanks
Barkat Mardhani
Neil Laurance
Ranch Hand

Joined: Jul 18, 2002
Posts: 183
You shouldn't redeclare the integer in the subclases. An example of how to obtain the effect you want:

Cheers, Neil
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
The thing to remember is that if you DO redeclare the variable in the sub-class, then the object ends up with BOTH. It inherits the Level1:x - so there is a field in the object that tracks that value, and then it creates it's OWN Level2:x which has a different field in the object to track THAT value. The Level2:x hides the Level1:x for variables of type Level2.
Then - depending on which version of x is requested, the proper one is delivered up. In your example the obj1, obj3 and obj3 variables are all type Level1, so the Level1:x variable is delivered up.
In Neils example the subclasses do not redeclare the variable, so there is just ONE field in the instances and it is Level1:x which is inherited by the subclasses. Instead he just manipulates the contents of that variable.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Is that by design in Java or a limition or my misunderstanding?
It's by design. Dynamic resolution of fields would make things run a little slower, and there's really no reason to need it, since you can make fields private and access them with method, which are dynamically resolved. So fields are resolved at compile time instead.


"I'm not back." - Bill Harding, Twister
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Polymorphism on data members