Interfaces
Learning Objectives
- You're familiar with the concept of an interface, can define your own interfaces, and implement an interface in a class.
- You know how to use interfaces as variable types, method parameters and method return values.
- You're aware of some of the interfaces that come with Java.
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. Let's examine a Readable interface that describes readability.
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. Let's create a class called TextMessage that implements the Readable interface.
Since the TextMessage class implements the Readable interface [public class TextMessage implements Readable], the TextMessage class must contain an implementation of the public String read[] method. Implementations of methods defined in the interface must always have public as their visibility attribute.
An Interface Is a Contract of Behaviour
When a class implements an interface, it signs an agreement. The agreement dictates that the class will implement the methods defined by the interface. If those methods are not implemented in the class, the program will not function.
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.
In addition to the TextMessage class, let's add another class that implements the Readable interface. The Ebook class is an electronic implementation of a book that containing the title and pages of a book. The ebook is read page by page, and calling the public String read[] method always returns the next page as a string.
Objects can be instantiated from interface-implementing classes just like with normal classes. They're also used in the same way, for instance, as an ArrayList's type.
It's going great!