Java Reference
In-Depth Information
LISTING 7.8
//********************************************************************
// Complexity.java Author: Lewis/Loftus
//
// Represents the interface for an object that can be assigned an
// explicit complexity.
//********************************************************************
public interface Complexity
{
public void setComplexity ( int complexity);
public int getComplexity();
}
A Java interface is a collection of constants and abstract methods.
An abstract method is a method that does not have an implemen-
tation. That is, there is no body of code defined for an abstract
method. The header of the method, including its parameter list, is
simply followed by a semicolon. An interface cannot be instantiated.
Listing 7.8 shows an interface called Complexity . It contains two
abstract methods: setComplexity and getComplexity .
An abstract method can be preceded by the reserved word abstract , though in
interfaces it usually is not. Methods in interfaces have public visibility by default.
A class implements an interface by providing method implementations for
each of the abstract methods defined in the interface. A class that implements an
interface uses the reserved word implements followed by the interface name in
the class header. If a class asserts that it implements a particular interface, it must
provide a definition for all methods in the interface. The compiler will produce
errors if any of the methods in the interface are not given a definition in the class.
The Question class, shown in Listing 7.9, implements the Complexity inter-
face. Both the setComplexity and getComplexity methods are implemented.
They must be declared with the same signatures as their abstract counterparts
in the interface. In the Question class, the methods are defined simply to set or
return a numeric value representing the complexity level of the question that the
object represents.
Note that the Question class also implements additional methods that are not
part of the Complexity interface. Specifically, it defines methods called getQues-
tion , getAnswer , answerCorrect , and toString , which have nothing to do with
the interface. The interface guarantees that the class implements certain methods,
KEY CONCEPT
An interface is a collection of
abstract methods and therefore can-
not be instantiated.
 
Search WWH ::




Custom Search