Java Reference
In-Depth Information
// Move the Pen using relative cocordinates
p1.move(5.0, 2.0);
System.out.println(p1);
}
}
Another common use of default methods is to declare optional methods in an interface. Consider a Named
interface as shown in Listing 17-14.
Listing 17-14. A Named Interface Using Default Methods to Provide Optional Methods
// Named.java
package com.jdojo.interfaces;
public interface Named {
void setName(String name);
default String getName() {
return "John Doe";
}
default void setNickname(String nickname) {
throw new UnsupportedOperationException("setNickname");
}
default String getNickname() {
throw new UnsupportedOperationException("getNickname");
}
}
The interface provides specification for getting and setting the official name and nickname. Not everything has
a nickname. The interface provides methods to get and set the nickname as default methods making them optional.
If a class implements the Named interface, it can override the setNickname() and getNickname() methods to provide
implementation, if the class supports a nickname. Otherwise, the class does not have to do anything for these methods.
They simply throw a runtime exception to indicate that they are not supported. The interface declares the getName()
method as default and provides a sensible default implementation for it by return “John Doe” as the default name. The
classes implementing the Named interface are expected to override the getName() method to return the real name.
You have just touched the tip of the iceberg in terms of the benefits and power that default methods have brought
to the Java language. It has given a new life to the existing Java APIs. In Java 8, default methods have been added to
several interfaces in the Java library to provide more expressiveness and functionality for the existing APIs.
What are the similarities and differences between a concrete method in a class and a default method in an interface?
Both provide an implementation.
this in the same way. That is, the keyword this is the
reference of the object on which the method is called.
Both have access to the keyword
The major difference lies in the access to the state of the object. A concrete method in a class
can access the instance variables of the class. However, a default method does not have access
to the instance of variables of the class implementing the interface. The default method has
access to the other members of the interface, for example other methods, constants, and type
members. For example, the default method in the Movable interface is written using the other
member methods getX() , getY() , setX() , and setY() .
 
Search WWH ::




Custom Search