Java Reference
In-Depth Information
The default methods are a new, exciting feature in Java 8. Prior to Java 8, interfaces could have only abstract
methods. Why were default methods added in Java 8? The short answer is that they were added so the existing
interfaces may evolve. At this point, the answer may be hard to understand. Let's look at an example to clear it.
Suppose, prior to Java 8, you want create a specification for movable objects to describe their locations in a 2D
plane. Let's create the specification by creating an interface named Movable , as shown in Listing 17-10.
Listing 17-10. A Movable Interface
// Movable.java
package com.jdojo.interfaces;
public interface Movable {
void setX(double x);
void setY(double y);
double getX();
double getY();
}
The interface declares four abstract methods. The setX() and setY() methods let the a Movable change the
location using the absolute positioning. The getX() and getY() methods return the current location in terms of the x
and y coordinates.
Consider the Pen class in Listing 17-11. It implements the Movable interface, and as part of the specification, it
provides implementation for the four methods of the interface. The class contains two instance variables called x and
y to track the location of the pen.
Listing 17-11. A Pen Class That Implements the Movable Interface
// Pen.java
package com.jdojo.interfaces;
public class Pen implements Movable {
private double x;
private double y;
public Pen() {
// By default, the pen is at (0.0, 0.0)
}
public Pen(double x, double y) {
this.x = x;
this.y = y;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
 
Search WWH ::




Custom Search