abstract
methods and final
, static
fields. All methods and fields of an interface must be public.
However, unlike a class, an interface can be added to a class that is already a subclass of another class. Furthermore an interface can apply to members of many different classes. For instance you can define an Import
interface with the single method calculateTariff()
.
public interface Import {
public double calculateTariff();
}
You might want to use this interface on many different classes, cars among them but also for clothes, food, electronics and moore. It would be inconvenient to make all these objects derive from a single class.
Furthermore, each different type of item is likely to have a different means of calculating the tariff. Therefore you define an Import
interface and declare that each class implements Import
.
The syntax is simple. Import
is declared public so that it can be accessed from any class. It is also possible to declare that an interface is protected so that it can only be implemented by classes in a particular package. However this is very unusual. Almost all interfaces will be public. No interface may be private because the whole purpose of an Interface is to be inherited by other classes.
The interface
keyword takes the place of the class
keyword.
Line 3 looks like a classic method definition. It's public (as it must be). It's abstract, also as it must be. And it returns a double
.
The method's name is calculateTariff()
and it takes no arguments. The difference between thisa and a method in a class is that there is no method body. That remains to be created in each class that implements the interface.
You can declare many different methods in an interface. These methods may be overloaded. An interface can also have fields, but if so they must be final
and static
(in other words constants).