Java Reference
In-Depth Information
13.10.8 Interfaces vs. Abstract Classes
Both interfaces and abstract classes can be used to specify common behavior for objects. How
do you decide whether to use an interface or a class? In general, a strong is-a relationship
that clearly describes a parent-child relationship should be modeled using classes. For exam-
ple, since an orange is a fruit, their relationship should be modeled using class inheritance.
A weak is-a relationship, also known as an is-kind-of relationship, 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 inter-
face. A circle or a rectangle is a geometric object, so Circle can be designed as a subclass
of GeometricObject . Circles are different and comparable based on their radii, so Circle
can implement the Comparable interface.
Interfaces are more flexible than abstract classes, because a subclass can extend only one
superclass but can implement any number of interfaces. However, interfaces cannot contain
concrete methods. The virtues of interfaces and abstract classes can be combined by creat-
ing an interface with an abstract class that implements it. Then you can use the interface or
the abstract class, whichever is convenient. We will give examples of this type of design in
Chapter 20, Lists, Stacks, Queues, and Priority Queues.
13.35
Describe class design guidelines.
Check
Point
K EY T ERMS
abstract class 496
abstract method
marker interface
513
496
shallow copy
515
deep copy
516
subinterface
518
interface
496
C HAPTER S UMMARY
1.
Abstract classes are like regular classes with data and methods, but you cannot create
instances of abstract classes using the new operator.
2.
An abstract method cannot be contained in a nonabstract class. If a subclass of an
abstract superclass does not implement all the inherited abstract methods of the super-
class, the subclass must be defined as abstract.
3.
A class that contains abstract methods must be abstract. However, it is possible to define
an abstract class that doesn't contain any abstract methods.
4.
A subclass can be abstract even if its superclass is concrete.
5. An interface is a class-like construct that contains only constants and abstract methods.
In many ways, an interface is similar to an abstract class, but an abstract class can con-
tain constants and abstract methods as well as variables and concrete methods.
6. An interface is treated like a special class in Java. Each interface is compiled into a
separate bytecode file, just like a regular class.
7.
The java.lang.Comparable interface defines the compareTo method. Many classes
in the Java library implement Comparable .
 
 
Search WWH ::




Custom Search