File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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
JavaRanch » Java Forums » Java » Beginning Java
Reply locked 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
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
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.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Please do not cross post. That is how there came to be a duplicate in this forum. Continue the conversation here.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Polymorphism on data members