Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism on data members

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic