From the below code, the class B is the subclass of class A. After the instance a is created, the method go is called. Java run this method of the class B. And the value of the attribute x is changed within the method go. Then I display the value of the attribute x of a. The initial value of x in class A is shown. My question is why doesn't Java show the lastest value of x after the method go finish ?
output >> B.go() : x = 600 x = 10 ---------------------------- B.go() : x = 600 x = 600
The simple answer is: because that's the way it is specified.
Now, why has it been specified that way?
I guess there are mainly two reasons:
- in a good OO design, data should be private, anyway, in which case polymorphism isn't needed, and
- making fields polymorphic would make the JVM more complex and could lead to decreased performance.
As an aside, i don't know of any OO language where fields are polymorphic. So another reason could be tradition...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Originally posted by Ilja Preuss: As an aside, i don't know of any OO language where fields are polymorphic. So another reason could be tradition...
Fields in Scala are polymorphic. Actually, from the clients perspective there's no difference between fields and methods. Fields in a subclass can override no-argument method declarations in a parent class or trait. But Scala is a multi-paradigm language so maybe this doesn't come from the OO side of it's family. [ August 28, 2008: Message edited by: Garrett Rowe ]
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter