Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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.
The following list itemizes the members that are inherited by a subclass:
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.Creating a subclass can be as simple as including the
- Subclasses inherit those superclass members declared as
public
orprotected
.- 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.
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.
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:
Theclass Super { Number aNumber; } class Subbie extends Super { Float aNumber; }aNumber
variable inSubbie
hidesaNumber
inSuper
. But you can accessSuper
'saNumber
fromSubbie
withsuper.aNumbersuper
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.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.