Interfaces
When dealing with an abstract class, we sometimes see what's called an interface. An interface is a definition of all abstract methods however, unlike abstract methods within an abstract class, these methods defined in the interface can be used in any other class, regardless of being abstract or not.
Here is how to define an interface:
The methods that are defined in the interface DO NOT need the abstract keyword with them.
In order for a class to use an interface, it must use the keyword implements in it's class header. Here is the definition:
where Name is the name of the class and interfaceName is the name of the interface you will be implementing.
By default, all methods in an interface contain the keywords abstract public before each definition so these are not needed. You also cannot make the methods private or protected as this is not allowed in Java interfaces.
Let's look back at the previous chapter's example of the Food stores.
Here is the full example using an interface:
Example 1:
Simple Interface example
Download source code here (Right click - Save Target As... (zip file))
Since each subclass is inheriting all methods from the super class FoodStore, it is not necessary to place the implements Slogan in each subclass. If you did that, you would get an error citing that the method from the interface is undefined and the super class must implement the interface.
The output is also the same as the last chapter. All we did was change the abstract method in the class to an interface.
Interface constants
Constants can be placed in an interface. This is perfectly legal in Java.
Here is an interface example that uses a constant:
The output would simply be "Equal months!"
Constants are also declared to be public by the interface rules.