Sub topic 7
Implementing an Interface
In the last chapter you declared an interface. An interface is a list of methods that a type promises to have. On its own, an interface does nothing. Some class has to keep the promise by writing real code for each method. This chapter shows how a class does that, and what the compiler checks along the way.
The `implements` Keyword
A class uses the keyword implements to say it keeps an interface's promise. The class that does this is called an implementing class. It must give a body to every abstract method in the interface. A body is the code between { and } that does the work.
Here is a small interface and two classes that implement it:
interface Greeter {
String greet(String name);
}
class EnglishGreeter implements Greeter {
@Override
public String greet(String name) {
return "Hello, " + name + "!";
}
}
class SpanishGreeter implements Greeter {
@Override
public String greet(String name) {
return "¡Hola, " + name + "!";
}
}
public class Main {
public static void main(String[] args) {
EnglishGreeter english = new EnglishGreeter();
SpanishGreeter spanish = new SpanishGreeter();
System.out.println(english.greet("Ana")); // prints: Hello, Ana!
System.out.println(spanish.greet("Ana")); // prints: ¡Hola, Ana!
}
}Both classes promise the same thing: give them a name and they return a greeting. Each one keeps the promise in its own way. The interface says what. Each class says how.
The dashed arrow in the diagram means "implements". A solid arrow would mean "extends", which is the arrow you saw for subclasses.
Rule 1: Implement Every Abstract Method
If a class says implements Greeter but leaves out greet, the program will not compile. To compile is to turn your code into a program the computer can run. The compiler checks your code first and refuses if a promise is broken.
class Robot implements Greeter {
// no greet method here
}The compiler reports an error like this:
error: Robot is not abstract and does not override abstract method greet(String) in GreeterRead the message closely. It gives you two ways to fix it. You can add the missing method, or you can mark the class abstract. You will see the second option later in this chapter.
The method you write must match the interface's method. It needs the same name and the same parameter types, in the same order. If you write greet(int id) instead of greet(String name), Java treats it as a different method. The original promise is still not kept.
Rule 2: The Method Must Be `public`
Every abstract method in an interface is public, even if you do not write the word. This is called an implicit modifier: Java adds it for you. A later chapter covers implicit modifiers in detail.
A class cannot make the method less visible than the interface does. So you must write public on the implementing method. Beginners often forget this:
class QuietGreeter implements Greeter {
@Override
String greet(String name) { // missing public
return "hi " + name;
}
}The compiler says:
error: greet(String) in QuietGreeter cannot implement greet(String) in Greeter
attempting to assign weaker access privileges; was publicThe fix is one word. Change the line to public String greet(String name).
Rule 3: Use `@Override`
The @Override annotation is a label that tells the compiler, "this method keeps a promise from a parent type." It is optional, but you should always use it. If you misspell the method name, for example greeet, the compiler will warn you that nothing is being overridden. Without @Override, the typo would quietly become a new method, and you would get the "does not override abstract method" error with no clear hint about why.
Adding Your Own Fields and Methods
An implementing class is still a normal class. It can have fields, constructors, and extra methods that the interface never mentions.
interface Counter {
void increment();
int getCount();
}
class ClickCounter implements Counter {
private int count;
private final String label;
ClickCounter(String label) {
this.label = label;
}
@Override
public void increment() {
count++;
}
@Override
public int getCount() {
return count;
}
public void reset() { // extra method, not in Counter
count = 0;
}
public String getLabel() { // extra method, not in Counter
return label;
}
}
public class Main {
public static void main(String[] args) {
ClickCounter button = new ClickCounter("Buy button");
button.increment();
button.increment();
button.increment();
System.out.println(button.getLabel() + ": " + button.getCount()); // prints: Buy button: 3
button.reset();
System.out.println(button.getCount()); // prints: 0
}
}The interface only sets the minimum. A class must have at least those methods, and it may have more.
Extending and Implementing at the Same Time
A class can extend one parent class and also implement an interface. The order is fixed: extends comes first, then implements.
class Animal {
protected final String name;
Animal(String name) {
this.name = name;
}
}
interface Speaker {
String speak();
}
class Dog extends Animal implements Speaker {
Dog(String name) {
super(name);
}
@Override
public String speak() {
return name + " says woof";
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex");
System.out.println(d.speak()); // prints: Rex says woof
}
}If you write class Dog implements Speaker extends Animal, the code will not compile.
Partial Implementation with an Abstract Class
Remember the compiler's second suggestion: mark the class abstract. An abstract class may implement an interface without writing every method. Any method it skips becomes a job for its concrete subclasses. A concrete class is one you can create objects from with new.
interface Player {
void play();
void stop();
}
abstract class BasePlayer implements Player {
@Override
public void stop() {
System.out.println("Stopped.");
}
// play() is not written here, so BasePlayer must be abstract
}
class SongPlayer extends BasePlayer {
@Override
public void play() {
System.out.println("Playing a song.");
}
}
public class Main {
public static void main(String[] args) {
SongPlayer p = new SongPlayer();
p.play(); // prints: Playing a song.
p.stop(); // prints: Stopped.
}
}BasePlayer keeps half the promise. SongPlayer keeps the rest. The compiler checks that by the time you reach a concrete class, every method has a body.
Summary of the Rules
| Rule | What happens if you break it |
|---|---|
| Write every abstract method, or mark the class `abstract` | "is not abstract and does not override abstract method" |
| Match the name and parameter types exactly | The method counts as a new method, and the promise stays unkept |
| Declare the method `public` | "attempting to assign weaker access privileges" |
| Put `extends` before `implements` | Syntax error |
| Use `@Override` | Typos are not caught early |
A class can also implement more than one interface at a time. That gets its own chapter later.
Exercises
Exercise
Write an interface Taxable with one method double tax(double amount). Then write a class SalesTax that implements it and returns 8% of the amount. What does new SalesTax().tax(100.0) return?
Show answer
interface Taxable { double tax(double amount); } and class SalesTax implements Taxable { @Override public double tax(double amount) { return amount * 0.08; } }. The call returns 8.0.
Exercise
A class is declared as class Lamp implements Switchable and contains @Override void turnOn() { }. The interface declares void turnOn();. Why does this fail to compile, and how do you fix it?
Show answer
Interface methods are implicitly public, and the class method has package-private access, which is weaker. Change it to @Override public void turnOn() { }.
Exercise
An interface Shape has two methods, area() and perimeter(). Class Base implements Shape but writes only perimeter(). What must be true about Base, and what must a concrete subclass of Base do?
Show answer
Base must be declared abstract, because it does not write area(). A concrete subclass must write area(). It inherits perimeter() from Base, so it does not have to write that one.