Design Patterns Java™ Workbook

(Michael S) #1
Chapter 2. Introducing Interfaces

package com.oozinoz.simulation;
import com.oozinoz.units.*;
interface RocketSim
{
abstract Length apogee();
public Force thrust();
}


Classes that provide rocket simulations implement the RocketSim interface. A rocket's
apogee and thrust are quantities that combine a magnitude with the physical dimensions of
length and force, respectively. (Chapter 3, Adapter, has more information about the units
package, on page 24.


CHALLENGE 2.2


Which of the following statements are true?

A. Both methods of the RocketSim interface are abstract, although only
apogee() declares this explicitly.
B. Both methods of the interface are public, although only thrust() declares
this explicitly.
C. All interfaces are public, so RocketSim is public, although it does not
declare this explicitly.
D. It is possible to create another interface, say, RocketSimSolid, that
extends RocketSim.
E. Every interface must have at least one method.
F. An interface can declare instance fields that an implementing class must also
declare.
G. Although you can't instantiate an interface, an interface definition can
declare constructor methods that require an implementing class to
provide constructors with given signatures.

Interfaces and Obligations..........................................................................................................................


A developer who creates a class that implements RocketSim is responsible for writing
apogee() and thrust() methods that return measures of a rocket's performance. In other
words, the developer must fulfill the contract implied by the method names and the code
comments.


Sometimes, the methods that an interface designates do not carry an obligation to perform a
service for the caller. In some cases, the implementing class can even ignore the call,
implementing a method with no body whatsoever.

Free download pdf