Java Reference
In-Depth Information
Now any class that implements the Sized interface will automatically inherit the implementation
of isEmpty. Consequently, adding a method to an interface with a default implementation isn't a
source incompatibility.
Let's go back to our initial example of the Java drawing library and your game. Concretely, to
evolve your library in a compatible way (which means the users of your library don't have to
modify all their classes that implement Resizable), use a default method and provide a default
implementation for setRelativeSize:
default void setRelativeSize(int wFactor, int hFactor){
setAbsoluteSize(getWidth() / wFactor, getHeight() / hFactor);
}
Because interfaces can now have methods with implementation, does that mean multiple
inheritance has arrived in Java? What happens if an implementing class also defines the same
method signature or if default methods can be overridden? Don't worry about these issues for
now; there are a few rules to follow and mechanisms available for you to deal with these issues.
We explore them in detail in section 9.5 .
You may have guessed that default methods are used extensively in the Java 8 API. You saw in
the introduction of this chapter that the stream method in the Collection interface we used
extensively in previous chapters is a default method. The sort method in the List interface is also
a default method. Many of the functional interfaces we presented in chapter 3 such as Predicate,
Function, and Comparator also introduced new default methods such as Predicate.and or
Function.andThen (remember, a functional interface contains only one abstract method; default
methods are non-abstract methods).
Abstract classes vs. interfaces in Java 8
So what's the difference between an abstract class and an interface? They both can contain
abstract methods and methods with a body.
First, a class can extend only from one abstract class, but a class can implement multiple
interfaces.
Second, an abstract class can enforce a common state through instance variables (fields). An
interface can't have instance variables.
Search WWH ::




Custom Search