Java Reference
In-Depth Information
An interface can inherit other interfaces using the extends keyword. Such an interface is
called a subinterface . For example, NewInterface in the following code is a subinterface of
Interface1 , . . . , and InterfaceN .
subinterface
public
interface
NewInterface
extends
Interface1, . . . , InterfaceN {
// constants and abstract methods
}
A class implementing NewInterface must implement the abstract methods defined in
NewInterface , Interface1 , . . . , and InterfaceN . An interface can extend other inter-
faces but not classes. A class can extend its superclass and implement multiple interfaces.
All classes share a single root, the Object class, but there is no single root for interfaces.
Like a class, an interface also defines a type. A variable of an interface type can reference any
instance of the class that implements the interface. If a class implements an interface, the
interface is like a superclass for the class. You can use an interface as a data type and cast a
variable of an interface type to its subclass, and vice versa. For example, suppose that c is an
instance of Class2 in Figure 15.7. c is also an instance of Object , Class1 , Interface1 ,
Interface1_1 , Interface1_2 , Interface2_1 , and Interface2_2 .
Interface 1_2
Interface 2_2
Interface 1_1
Interface 1
Interface 2_1
Object
Class1
Class2
F IGURE 15.7 Class1 implements Interface1 ; Interface1 extends Interface1_1
and Interface1_2 . Class2 extends Class1 and implements Interface2_1 and
Interface2_2 .
Note
Class names are nouns. Interface names may be adjectives or nouns.
naming convention
Design Guide
Abstract classes and interfaces can both be used to specify common behavior of objects.
How do you decide whether to use an interface or a class? In general, a strong is-a rela-
tionship that clearly describes a parent-child relationship should be modeled using
classes. For example, Gregorian calendar is a calendar, so the relationship between the
class java.util.GregorianCalendar and java.util.Calendar is modeled
using class inheritance. A weak is-a relationship , also known as an is-kind-of relation-
ship , indicates that an object possesses a certain property. A weak is-a relationship can
be modeled using interfaces. For example, all strings are comparable, so the String
class implements the Comparable interface.
is-a relationship
is-kind-of relationship
In general, interfaces are preferred over abstract classes because an interface can
define a common supertype for unrelated classes. Interfaces are more flexible than
interface preferred
 
Search WWH ::




Custom Search