Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces

Subclasses, Superclasses, and Inheritance

In Java, as in other object-oriented programming languages, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass. The class from which its derived is called the superclass.

In fact, in Java, all classes must be derived from some class. Which leads to the question "Where does it all begin?" The top-most class, the class from which all other classes are derived, is the Object class defined in java.lang. Object is the root of a hierarchy of classes.

The subclass inherits state and behavior in the form of variables and methods from its superclass. The subclass can just use the items inherited from its superclass as is, or the subclass can modify or override it. So, as you drop down in the hierarchy, the classes become more and more specialized:

Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.
Now would be a good time to review the discussion in What Is Inheritance?(in the Writing Java Programs trail).

Creating Subclasses

To create a subclass of another class use the extends clause in your class declaration. (The Class Declaration explains all of the components of a class declaration in detail.) As a subclass, your class inherits member variables and methods from its superclass. Your class can choose to hide variables or override methods inherited from its superclass.

Writing Final Classes and Methods

Sometimes, for security or design reasons, you want to prevent your class from being subclassed. Or, you may just wish to prevent certain methods within your class from being overriden. In Java, you can achieve either of these goals by marking the class or the method as final.

Writing Abstract Classes and Methods

On the other hand, some classes are written for the sole purpose of being subclassed (and are not intended to ever be instantiated). These classes are called abstract classes and often contain abstract methods.

The Object Class

All objects in the Java environment inherit either directly or indirectly from the Object class. This section talks about the interesting methods in Object--methods that you may wish to invoke or override.

Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces