Java Reference
In-Depth Information
Organizing Classes and Class Behavior
An introduction to object-oriented programming in Java isn't complete without looking
at three more concepts: inheritance, interfaces, and packages.
These three concepts are mechanisms for organizing classes and class behavior.
Inheritance
Inheritance is one of the most crucial concepts in object-oriented programming, and it
has a direct effect on how you design and write your own Java classes.
Inheritance is a mechanism that enables one class to inherit all the behavior and attrib-
utes of another class.
Through inheritance, a class immediately picks up all the functionality of an existing
class. Because of this, you only must define how the new class is different from an exist-
ing class.
With inheritance, all classes—those you create and those from the Java class library and
other libraries—are arranged in a strict hierarchy.
A class that inherits from another class is called a subclass . The class that gives the
inheritance is called a superclass .
A class can have only one superclass, but each class can have an unlimited number of
subclasses. Subclasses inherit all the attributes and behavior of their superclasses.
In practical terms, this means that if the superclass has behavior and attributes that your
class needs, you don't have to redefine it or copy that code to have the same behavior
and attributes. Your class automatically receives these things from its superclass, the
superclass gets them from its superclass, and so on, all the way up the hierarchy. Your
class becomes a combination of its own features and all the features of the classes above
it in the hierarchy.
The situation is comparable to the way you inherited traits from your parents, such as
your height, hair color, and love of peanut butter and banana sandwiches. They inherited
some of these things from their parents, who inherited from theirs, and backward through
time to the Garden of Eden, Big Bang, or [insert personal belief here] .
Figure 1.2 shows the way a hierarchy of classes is arranged.
At the top of the Java class hierarchy is the class Object —all classes inherit from this
superclass. Object is the most general class in the hierarchy, and it defines behavior
inherited by all the classes in the Java class library.
 
Search WWH ::




Custom Search