Interfaces
Interfaces allow you to abstract the workings of your code and provide simple interfaces to the user:
Lamp Example
public interface Switchable {
public void switchOn();
public void switchOff();
}
This defines the interface type that someone can call.
Switchable l = new Lamp();
l.switchOn();
l.switchOff();
This is the use for the interface.
public class Lamp implements Switchable {
public void switchOn() {
// method
}
public void switchOff() {
// method
}
}
This is the implementation of the interface.
Interfaces
In java, an interface is a specification which public methods must exist in a class that implements it.
This is like a contract that the front and back-end programmers must adhere to.
- Interfaces define a type.
- Typically only contains constants and methods signatures.
- Not the method bodies.
- Cannot be instantiated.
- Can be implemented by a class, which then has to contain all method bodies declared in the interface.
- Can be extended by other interfaces.
- A class can implement more than one interface.
Extending Interfaces
A class can implement several interfaces. Such a class would have to implement all methods from all the interfaces it implements.
public class Lamp implements Switchable, Pluggable {
// Switchable methods
// Plugable methods
}
An interface can itself extend one or more other interfaces:
interface Dimmable extends Switchable, Plugable {
...
}
This means that if you want to provide Dimmable
then you have to provide implementations for all the methods in the other interfaces.
An interface cannot implement other interfaces:
public interface Dimmable implements Switchable {
...
}
This does not work.
Implementing Multiple Interfaces in a class
A class can also extend from other classes while implementing interfaces:
public class Lamp extends Furnature implements Switchable, Pluggable {
// Switchable methods
// Plugable methods
}
Conventions
- Interface identifiers end in “-able”:
java.Lang.Comparable
java.io.Serializable
- All interface methods are
public
andabstract
. - All attributes are
public
,static
andfinal
.
Interfaces vs. Abstract Classes
Abstract Classes | Interfaces |
---|---|
Can only extend one superclass. |
Multiple inheritance between interfaces. |
Can extend any class. |
Can only extend interfaces. |
May have abstract and concrete methods. |
Only abstract methods. |
protected methods allowed. |
Methods are public abstract . |
No restriction on attribute modifiers. | Only public static final variables. |
- The purpose of abstract classes is to provide abstraction when designing type hierarchies or class hierarchies.
- Interfaces are for specifying the
public
facing services or to coordinate several groups of programmers/software.