Abstract classesand methods
Interfaces
However, an interface is more than just an abstract class taken to the extreme, since it allows you to perform a variation of "multiple inheritance" by creating a class that can be upcast to more than one base type.
To create an interface, use the
interfacekeyword instead of the
classkeyword. As with a class, you can add the
publickeyword before the
interfacekeyword (
but only if that interface is defined in a file of the same name). If you leave off the
publickeyword, you get package access, so the interface is only usable within the same package.
An interface can also contain fields, but these are implicitly
static
and
final.
Complete decoupling
Creating a method that behaves differently depending on the argument object that you pass it is called the Strategy design pattern. The method contains the fixed part of the algorithm to be performed, and the Strategy contains the part that varies. The Strategy is the object that you pass in, and it contains code to be executed.
“Multiple inheritance” in Java
When you combine a concrete class with interfaces thisway, the concrete class must come first, then the interfaces.
Extending an interfacewith inheritance
Name collisions when combining Interfaces
Adapting to an interface
Because you can add an interface onto any existing class in this way, it means that a method that takes an interface provides a way for any class to be adapted to work with that method.This is the power of using interfaces instead of classes.
Fields in interfaces
Because any fields you put into an interface are automatically
static
and
final
, the interface is a convenient tool for creating groups of constant values.
Initializing fields in interfaces
Since the fields are
static
, they are initialized when the class is first loaded, which happenswhen any of the fields are accessed for the first time.
Nesting interfaces
Interfaces may be nested within classes and within other interfaces.
As an added twist,
interfaces can also be private,
notice that when you implement an interface, you are not required to implementany interfaces nested within. Also, private interfaces cannot be implemented outside oftheir defining classes.
Interfaces and factories