Java Reference
In-Depth Information
3.4.2
Inheritance is how a class places itself in a hierarchy of existing classes. In Java,
each class inherits from exactly one existing class. A class names the class from
which it inherits with the extends keyword. We said a Java class inherits from
exactly one class, and yet our Example 3.24 doesn't contain the extends
keyword. What gives?
If a class doesn't explicitly extend an existing class, it implicitly extends
the “root” Java class, Object . The Object class has some interesting features,
and the fact that all Java classes directly or indirectly extend Object has
interesting consequences that we will explore later.
Persons coming to Java from another object-oriented language whose
name shall remain C++ might wonder about multiple inheritance. Java has the
concept of interfaces . An interface is like a class, except that it may not contain
data 10 and may contain only method definitions, without any implementation
(Example 3.25). An interface may not be instantiated (created with the new
operator), 11 so how do you make use of interfaces? Well, a class extends exactly
one existing base class, but it may implement any number of interfaces by using
the implements keyword (Example 3.26).
Inheritance
Example 3.25 An interface
public interface
Identifiable
{
public int getID();
}
As you can see, a class that implements an interface must provide an imple-
mentation of all the methods defined in the interface. We said that an interface
cannot be instantiated, but you can declare a variable of type Identifiable
10. Actually, an interface may contain final static data, but since we haven't introduced
these concepts yet, just pretend interfaces cannot contain data for now and we'll put the lie to
it later.
11. Although you can do something that looks suspiciously like it with anonymous inner
classes —but since we haven't introduced these concepts yet, just pretend that you cannot instan-
tiate an interface; you will see such use later.
Search WWH ::




Custom Search