Interfaces
Prerequisites: Abstraction & abstract classes
An interface defines a contract — a set of methods a class
promises to implement — with no fields of its own (beyond
constants) and no inheritance limit: a class can implement any
number of interfaces.
interface Payable {
double calculatePay();
}
interface Named {
String getName();
}
class Employee implements Payable, Named {
String name;
double hourlyRate;
int hoursWorked;
Employee(String name, double hourlyRate, int hoursWorked) {
this.name = name;
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
@Override
public double calculatePay() {
return hourlyRate * hoursWorked;
}
@Override
public String getName() {
return name;
}
}
Since Java 8, an interface can also provide a default method with a
body — used sparingly, mainly to add a new method to an interface
without breaking every existing implementer.
Common mistakes
- Reaching for an
abstract classwhen there's no shared field or constructor logic to reuse — aninterfaceis usually the better fit, and doesn't use up a class's oneextendsslot.
Practice
Define an interface Describable with a method describe()
returning a String, and implement it on a simple class.
Show solution
interface Describable {
String describe();
}
class Book implements Describable {
String title;
Book(String title) {
this.title = title;
}
@Override
public String describe() {
return "Book: " + title;
}
}