ghanoz2480 wrote:
I read a tutorial about inheritance (http://java.sun.com/docs/books/
tutorial/java/IandI/subclasses.html) and i want to ask why when we can
declare a field in the subclass with the same name as the one in the
superclass, it is not recommended?
Anybody can help explained about it? Or have a "good resource" to
share me about that question? Thank you.
It is normal for a subclass to override a superclass'
method by providing a method of its own with the same name
and parameter list, so that the subclass can specialize its
behavior. For example, it is normal to override Object's
toString() method so that a subclass can provide a String
representation that is meaningful. Specializing behavior
by overriding methods is one of the main purposes of class
inheritance.
Data fields are a little different. Usually they record
the state of an object, while the methods provide behavior.
Usually, the fact that a superclass has been extended by a
subclass does not affect the state of an instance when it
is viewed in its superclass role. JButton is a subclass of
JComponent, so a JButton instance "is a" JComponent instance.
But every JComponent maintains state that does not depend on
whether the JComponent is free-standing, or is a JButton, or
is a JList. The data fields "belonging" to its JComponent
role are maintained the same way regardless of subclassing.
The Java language reflects these two purposes by treating
methods and fields differently. If a subclass overrides a
superclass' method, all calls to that method name execute the
subclass' version -- even calls made from the superclass' own
code invoke the subclass' overriding method. But data fields
do not share this behavior: When the superclass' code refers
to a field named myField, it always uses the superclass' own
myField even if the subclass also has a field named myField.
Methods can be overridden, data fields cannot.
Since methods can be overridden, it is normal to re-use
the same name to refer to the superclass' method and to the
subclass' method that overrides it: Object has toString() and
Double has toString() and AbstractList has toString() and so
it goes. But since data fields cannot be overridden, the only
result of re-using the same name for an entirely different
field is confusion. It is not an override, but using the same
name makes it *look* like an override, and it is seldom a good
idea for code to look like something it actually isn't.
Language Specification (JLS).