interfaces
are the primary means of decoupling the uses of a class from its implementation.
This decoupling provides flexibility for maintenance of the implementation and helps support type safe generic behavior.
The syntax of an interface is similar to that of a class except that methods appear as the signature only and no body is provided.
public interface Language {
String speak();
}
public interface ItalianLanguage extends Language {
String speak();
String speakItalian();
}
public interface ScriptConverter {
void setVersion(String version);
String getVersion();
String convertCyrillicToLatin(String cyrillic);
}
The implementing class must implement all operations defined by the interface.
Interfaces typically do one or more of the following:
Comparable<T>
)public class ItalianTraveller implements ItalianLanguage {
public String speak() {
return "Ciao mondo";
}
public String speakItalian() {
return speak();
}
}
public class ItalianTravellerV2 implements ItalianLanguage {
public String speak() {
return "migliorata - Ciao mondo";
}
public String speakItalian() {
return speak();
}
}
public class FrenchTraveller implements Language {
public String speak() {
return "Ça va?";
}
}
public class RussianTraveller implements Language, ScriptConverter {
private String version;
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public String speak()
{
return "Привет мир";
}
public String convertCyrillicToLatin(String cyrillic) {
throw new UnsupportedOperationException();
}
}
public class DocumentTranslator implements ScriptConverter {
private String version;
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public String translate(String russian) {
throw new UnsupportedOperationException();
}
public String convertCyrillicToLatin(String cyrillic) {
throw new UnsupportedOperationException();
}
}
Code which uses the above interfaces and classes can:
Interfaces are widely used to support testing as they allow for easy mocking.
Interfaces can extend other interfaces with the extend
keyword.
Members of an interface are public by default.
Interfaces can contain nested types: interfaces
, enums
and classes
.
Here, the containing interfaces act as namespaces.
Nested types are accessed outside the interface by prefixing the interface name and using dot syntax to identify the member.
By design, Java does not support multiple inheritance, but it facilitates a kind of multiple inheritance through interfaces.
Moreover, the concept of polymorphism can be implemented through interfaces underpins the interface mechanism.