This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
    Bookmark Topic Watch Topic
  • New Topic

Polymorphism on data members

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
That is by design. Variables are resolved at compile time and do not participate in polymorphism. The value that is used is determined by the TYPE of the variable.
In your example all three variables are of type Level1 and therefore that is the version of the variable that is used.
PS: This has nothing to do with Servlets, so I am moving it to Beginner.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please do not cross post. That is how there came to be a duplicate in this forum. Continue the conversation here.
 
I agree. Here's the link: http://aspose.com/file-tools
    Bookmark Topic Watch Topic
  • New Topic