Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 5 Object-Oriented Design Principles

to its clients by defining an abstraction. All the classes implementing the interface provide their own implementations for the promised functionality.

Let’s elucidate Java interfaces with an example. Consider the java.lang.Comparable interface that specifies the following protocol:

public interface Comparable{

public int compareTo(Object o);

//Intent is to compare this object with the specified object

//The return type is integer. Returns negative,

//zero or a positive value when this object is less than,

//equal to, or greater than the specified object

}

Unrelated classes can provide their own implementations when they implement Comparable. These unrelated classes have one aspect in common: they all follow the specification given by Comparable, and it is left to the implementation of these individual classes to implement compareTo() accordingly. Data structures supported

in the java.util package implement this interface. If you want to use the general algorithms provided in the library, you have to implement this interface. For example, consider the sample implementation of max() method in java.util.Collections. It is meant for finding the maximum element in a collection. It uses the Comparable interface, and the elements in the collection must provide the implementation for the compareTo() method.

The algorithms (i.e., clients of the interface) are completely ignorant about how the compareTo() method is implemented. But the clients know the contract that insures the availability of the compareTo() method, hence clients can use it. This confers a very important advantage: when a method takes an interface as an argument, you can pass any object that implements that interface (due to runtime polymorphism).

Conceptually, a class and an interface are two different constructs used for two different purposes. A class combines the state and the behavior of a real object, whereas an interface specifies the behavior of an abstract entity.

Declaring and Using Interfaces

Now it’s time to implement your own interface for shape objects. Some circular shaped objects (such as Circle and Ellipse) can be rolled to a given degree. You can create a Rollable interface and declare a method named roll() where

interface Rollable {

void roll(float degree);

}

As you can see, you define an interface using the interface keyword. You can declare methods in that interface; here it is the roll() method. The method takes one argument: the degree for rolling. Now let’s implement the interface for Circle, which is Rollable.

class Circle implements Rollable { public void roll(float degree) {

/* implement rolling functionality here */

}

}

You use the implements keyword for implementing an interface. Note that the method name, its argument, and the return type in the class definition should exactly match the one given in the interface; if they don’t match, the class is not considered to implement that interface.

If you are implementing an interface in an abstract class, the abstract class does not need to define the method.

114

Chapter 5 Object-Oriented Design Principles

interface Rollable {

void roll(float degree);

}

abstract class CircularShape implements Rollable extends Shape { }

In this case, CircularShape implements a Rollable interface and extends the Shape abstract class (as you saw in Chapters 3 and 4). Now the concrete classes like Circle and Ellipse can extend this abstract class and define the roll() method.

The Rollable example you saw has only one method—roll(). However, it is common for interfaces to have multiple methods. For example, java.util defines the Iterable interface as follows:

public interface Iterator<E> { boolean hasNext();

E next(); void remove();

}

This interface is meant for traversing a collection. (Don’t worry about the “<E>” in Iterator<E>. It refers to the element type and falls under generics, which we cover in detail in the next chapter). It declares three methods: hasNext(), next(), and remove().

In fact, a class can implement multiple interfaces at the same time—both directly and indirectly through its base classes. For example, the Circle class can also implement the standard Cloneable interface (for creating copies of the Circle object) and the Serializable interface (for storing the object in files to recreate the object later, etc.), like so:

class Circle extends CircularShape implements Cloneable, Serializable { /* definition of methods such as clone here */

}

Points to Remember

Here are some key rules about interfaces that will help you in the OCPJP 7 exam:

An interface cannot be instantiated.

An interface can extend another interface. Use the extends (and not the implements) keyword for this.

Interfaces cannot contain instance variables. If you declare a data member in an interface, it should be initialized, and all such data members are implicitly treated as “public static final” members.

An interface cannot declare static methods. It can only declare instance methods.

You cannot declare members as protected or private. Only public access is allowed for members of an interface.

All methods declared in an interface are implicitly considered to be abstract. If you want, you can explicitly use the abstract qualifier for the method.

You can only declare (and not define) methods in an interface.

115

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]