Java Reference
In-Depth Information
Two of our abstract classes in the example above, Actor and Drawable , are good candidates
for being written as interfaces. Both of them contain only the definition of methods, without
method implementations. Thus, they already fit the definition of an interface perfectly: they
contain no instance fields, no constructors, and no method bodies.
The class Animal is a different case. It is a real abstract class that provides a partial implemen-
tation (many methods have method bodies) and only a single abstract method in its original
version. So it must remain as a class rather than becoming an interface.
Exercise 10.53 Redefine as an interface the abstract class Actor in your project. Does the
simulation still compile? Does it run? Make any changes necessary to make it runnable again.
Exercise 10.54 Are the fields in the following interface class fields or instance fields?
public interface Quiz
int CORRECT = 1;
int INCORRECT = 0;
What visibility do they have?
Exercise 10.55 What are the errors in the following interface?
public interface Monitor
private static final int THRESHOLD = 50;
public Monitor (int initial);
public int getThreshold()
Multiple inheritance of interfaces
As mentioned above, Java allows any class to extend at most one other class. However, it
allows a class to implement any number of interfaces (in addition to possibly extending one
class). Thus, if we define both Actor and Drawable as interfaces instead of abstract classes,
we can define class Hunter (Figure 10.4) to implement both of them:
public class Hunter implements Actor, Drawable
// Body of class omitted.
Search WWH ::

Custom Search