Trail: Learning the Java Language
|
Lesson: More Features of the Java Language
|
|
Understanding Inheritance
A subclass inherits variables and methods from its superclass and all
of its ancestors. The subclass can use these members as is, or it can
hide the member variables or override the methods.
What Members Does a Subclass Inherit?
Rule: A subclass inherits all of the members in its
superclass that are accessible to that subclass unless the subclass
explicitly hides a member variable or overrides a method. Note that
constructors are not members and are not inherited by subclasses.
The following list itemizes the members that are inherited by a subclass:
-
Subclasses inherit those superclass members declared as
public or protected.
-
Subclasses inherit those superclass members declared with no access
specifier as long as the subclass is in the same package as the
superclass.
-
Subclasses don't inherit a superclass's member if the subclass declares
a member with the same name. In the case of member variables, the
member variable in the subclass hides the one in the superclass. In the
case of methods, the method in the subclass overrides the one in the
superclass.
-
Subclasses don't inherit the superclass's
private members.
Creating a subclass can be as simple as including the extends
clause in your class declaration. However, you usually have to make other
provisions in your code when subclassing a class, such as overriding
methods or providing implementations for abstract methods.
Hiding Member Variables
As mentioned in the previous section, member variables defined in the
subclass hide member variables that have the same name in the
superclass.
While this feature of the Java language is powerful and convenient, it
can be a fruitful source of errors. When naming your member variables,
be careful to hide only those member variables that you actually wish
to hide.
One interesting feature of Java member variables is that a class can
access a hidden member variable through its superclass. Consider the
following superclass and subclass pair:
class Super {
Number aNumber;
}
class Subbie extends Super {
Float aNumber;
}
The aNumber variable in Subbie hides
aNumber in Super. But you can access
Super's aNumber from Subbie
with
super.aNumber
super is a Java language keyword that allows a method to
refer to hidden variables and overridden methods of the superclass.
The ability of a subclass to override a method in its superclass allows
a class to inherit from a superclass whose behavior is "close enough"
and then supplement or modify the behavior of that superclass.
|