6.13. Interfaces
In the classes that you derived from the class Animal, you had a common method, sound(), that was implemented individually in each of the subclasses. The method signature was the same in each class, and the method could be called polymorphically. The main point to defining the class Animal first and then subsequently defining the classes Dog, Cat, and so on, from it was to be able to get polymorphic behavior. When all you want is a set of one or more methods to be implemented in a number of different classes so that you can call them polymorphically, you can dispense with the base class altogether.
You can achieve the same result much more simply by using a Java facility called an interface. The name indicates its primary use—specifying a set of methods that represent a particular class interface, which can then be implemented appropriately in a number of different classes. All of the classes will then share this common interface, and the methods in it can be called polymorphically through a variable of the interface type. This is just one aspect of what you can do using an interface. I will start by examining what an interface is from the ground up and then look at what you can do with it.
An interface is essentially a collection of related constants and/or abstract methods, and in most cases it will contain just methods. An interface doesn't define what a method does. It just defines its form—its name, its parameters, and its return type, so by definition the ...
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.