Java Reference
In-Depth Information
ments a Java SE 8 interface, the class “signs a contract” with the compiler that says, “I will
declare all the abstract methods specified by the interface or I will declare my class
abstract ”—the implementing class is not required to override the interface's default
methods, but it can if necessary.
Software Engineering Observation 10.11
Java SE 8 default methods enable you to evolve existing interfaces by adding new
methods to those interfaces without breaking code that uses them.
Interfaces vs. abstract Classes
Prior to Java SE 8, an interface was typically used (rather than an abstract class) when
there were no implementation details to inherit—no fields and no method implementa-
tions. With default methods, you can instead declare common method implementations
in interfaces, which gives you more flexibility in designing your classes.
10.10.2 static Interface Methods
Prior to Java SE 8, it was common to associate with an interface a class containing static
helper methods for working with objects that implemented the interface. In Chapter 16,
you'll learn about class Collections which contains many static helper methods for
working with objects that implement interfaces Collection , List , Set and more. For ex-
ample, Collections method sort can sort objects of any class that implements interface
List . With static interface methods, such helper methods can now be declared directly
in interfaces rather than in separate classes.
10.10.3 Functional Interfaces
As of Java SE 8, any interface containing only one abstract method is known as a func-
tional interface . There are many such interfaces throughout the Java SE 7 APIs, and many
new ones in Java SE 8. Some functional interfaces that you'll use in this topic include:
ActionListener (Chapter 12)—You'll implement this interface to define a
method that's called when the user clicks a button.
Comparator (Chapter 16)—You'll implement this interface to define a method
that can compare two objects of a given type to determine whether the first object
is less than, equal to or greater than the second.
Runnable (Chapter 23)—You'll implement this interface to define a task that
may be run in parallel with other parts of your program.
Functional interfaces are used extensively with Java SE 8's new lambda capabilities that we
introduce in Chapter 17. In Chapter 12, you'll often implement an interface by creating
a so-called anonymous inner class that implements the interface's method(s). In Java SE
8, lambdas provide a shorthand notation for creating anonymous methods that the compiler
automatically translates into anonymous inner classes for you.
10.11 (Optional) GUI and Graphics Case Study: Drawing
with Polymorphism
You may have noticed in the drawing program created in GUI and Graphics Case Study
Exercise 8.1 (and modified in GUI and Graphics Case Study Exercise 9.1) that shape
 
 
 
 
Search WWH ::




Custom Search