Java Reference
In-Depth Information
Introducing Interfaces (Chapter 2)
SOLUTION 2.1
An abstract class with no nonabstract methods is similar to an interface in terms of its utility.
However, note the following.
A class can implement any number of interfaces but can subclass at most one abstract
class.
An abstract class can have nonabstract methods, which are usually instances of the
T EMPLATE M ETHOD pattern. All the methods of an interface are abstract, whether or
not this declaration is explicit.
An abstract class can declare instance variables that its subclasses inherit. An interface
cannot declare instance variables, although it can establish static final fields.
An abstract class can define constructors; an interface cannot.
An abstract class's visibility can be public , protected , private , or none
(package); an interface's visibility must be public or none (package).
An abstract class can have methods whose visibility is protected , private , or
none (package); every method in an interface must be public .
An abstract class inherits from Object , including such methods as clone() and
equals() .
SOLUTION 2.2
A. True. Interface methods are always abstract, whether or not they declare it.
B. True. Interface methods are also always public, whether or not they declare it.
C. False! An interface's visibility may be limited to the package in which the interface
resides. The RocketSim interface does not declare itself to be public , so it is
package protected. Classes outside com.oozinoz.sim cannot access or implement
this interface.
D. True. For example, the List and the Set interfaces both extend the Collection
interface in java.util .
E. False. An interface with no methods is a marker interface. Sometimes, a method high
in a class hierarchy, such as Object.clone() , is not appropriate for every subclass.
You can create a marker interface that requires subclasses to opt in or to opt out of
participation in such a method. The clone() method on Object requires subclasses
to opt in, declaring that they implement the Cloneable marker interface.
F. False. An interface cannot declare instance fields, although it can create constants by
declaring fields that are static and final .
G. False. It might be a good idea, but there is no way for a Java interface to require
implementing classes to provide any particular constructors.
SOLUTION 2.3
An interface does not define a contract between the caller and the implementing class when
the interface is used to register for notification. In this case, the implementing class may need
to take an action in response to a method call, but it is generally not performing a service for
the caller.
Search WWH ::




Custom Search