Java Reference
In-Depth Information
public double getX() {
return x;
}
public double getY() {
return y;
}
public String toString() {
return "Pen(" + x + ", " + y + ")";
}
}
The following snippet of code uses the Movable interface and the Pen class:
// Create a Pen and assign its reference to a Movable variable
Movable p1 = new Pen();
System.out.println(p1);
// Move the Pen
p1.setX(10.0);
p1.setY(5.0);
System.out.println(p1);
Pen(0.0, 0.0)
Pen(10.0, 5.0)
So far, there is nothing extraordinary going on with the Movable interface and the Pen class. Suppose the Movable
interface is part of a library that you have developed. You have distributed the library to your customers. Customers
have implemented the Movable interface in their classes.
Now comes a twist in the story. Some customers have requested that the Movable interface include specifications
for changing the location using relative coordinates. They want you to add a move() method to the Movable interface
as follows. The requested part is shown in boldface.
public interface Movable {
void setX(double x);
void setY(double y);
double getX();
double getY();
void move(double deltaX, double deltaY);
}
You are a nice business person; you always want a happy customer. You obliged the customer. You made the
changes and redistributed the new version of your library. After a few hours, you get calls from several angry customers.
They are angry because the new version of the library broke their existing code. Let's analyze what went wrong.
Prior to Java 8, all methods in an interface were implicitly abstract. Therefore, the new method move() is an
abstract method. All classes that are implementing the Movable interface must provide the implementation for the
new method. Note that customers already have several classes, for example, the Pen class, implementing the Movable
interface. All those classes will not compile anymore unless the new method is added to those classes. The moral of
the story is that, prior to Java 8, it was not possible to add methods to an interface after it has been distributed to the
public, without breaking the existing code.
 
Search WWH ::




Custom Search