Java Reference
In-Depth Information
Java libraries have published hundreds of interfaces, which were used thousands of times by customers
worldwide. Java designers were in a dire need of a way to evolve the existing interfaces without breaking the existing
code. They explored several solutions. Default methods were the accepted solution to evolve interfaces. A default
method can be added to an existing interface. It provides a default implementation for the method. All classes
implementing the interface will inherit the default implementation, thus not breaking them. Classes may choose to
override the default implementation.
A default method is declared using the keyword default . A default method cannot be declared abstract or static.
It must provide an implementation. Otherwise, a compile-time error occurs. Listing 17-12 shows the revised code for
the Movable interface. It contains a default method move() that is defined in terms of the existing four methods.
Listing 17-12. The Movable Interface with a Default Method
// Movable.java
package com.jdojo.interfaces;
public interface Movable {
void setX(double x);
void setY(double y);
double getX();
double getY();
// A default method
default void move(double deltaX, double deltaY) {
double newX = getX() + deltaX;
double newY = getY() + deltaY;
setX(newX);
setY(newY);
}
}
Any existing classes, including the Pen class, that implement the Movable interface will continue to compile and
work as before. The new move() method with its default implementation is available for all those classes. Listing 17-13
shows the usage of the old and new methods of the Movable interface with the Pen class.
Listing 17-13. Testing the New Movable Interface with the Existing Pen Class
// MovableTest.java
package com.jdojo.interfaces;
public class MovableTest {
public static void main(String[] args) {
// Create a Pen and assign its reference to a Movable variable
Movable p1 = new Pen();
System.out.println(p1);
// Move the Pen using absolute cocordinates
p1.setX(10.0);
p1.setY(5.0);
System.out.println(p1);
 
Search WWH ::




Custom Search