We can use interfaces to define behavior that's required from a class, i.e., its methods.
They're defined the same way that regular Java classes are, but "public interface ...
" is used instead of "public class ...
" at the beginning of the class.
Interfaces define behavior through method names and their return values. However, they don't always include the actual implementations of the methods.
A visibility attribute on interfaces is not marked explicitly as they're always public
.
public interface Readable {
String read();
}
The Readable
interface declares a read()
method, which returns a String-type object. Readable defines certain behavior: for example, a text message or an email may be readable.
The classes that implement the interface decide how the methods defined in the interface are implemented.
A class implements the interface by adding the keyword implements after the class name followed by the name of the interface being implemented.
Implementations of methods defined in the interface must always have public as their visibility attribute.
<aside> 💡 The interface defines only the names, parameters, and return values of the required methods. The interface, however, does not have a say on the internal implementation of its methods. It is the responsibility of the programmer to define the internal functionality for the methods.
</aside>
An object's type can be other than its class. For example, the type of the Ebook
class that implements the Readable
interface is both Ebook
and Readable
. Similarly, the text message also has multiple types. Because the TextMessage
class implements the Readable
interface, it has a Readable
type in addition to the TextMessage
type. (This is polymorphism).
Readable readable = new TextMessage("ope", "TextMessage is Readable!"); // works
TextMessage message = readable; // doesn't work
TextMessage castMessage = (TextMessage) readable; // works if, and only if, readable is of text message type
Type conversion succeeds if, and only if, the variable is of the type that it's being converted to.
Type conversion is not considered good practice, and one of the few situation where it's use is appropriate is in the implementation of the equals
method.
The true benefits of interfaces are reaped when they are used as the type of parameter provided to a method.
Since an interface can be used as a variable's type, it can also be used as a parameter type in method calls.
public class Printer {
public void print(Readable readable) {
System.out.println(readable.read());
}
}
The value of the print
method of the printer
class lies in the fact that it can be given any class that implements the Readable
interface as a parameter.