What an interface is
An interface is a contract: a list of methods that a class promises to provide. It says what an object can do, and it leaves out how the object does it. A Truck, a Robot and a Drone have little in common as types, but all three can move. Put move() in a Movable interface, let each class implement it, and code that only needs something movable can work with all three.
Inheritance models "is a": a Dog is an Animal. An interface models "can do": a Dog can speak. That difference decides when to use which.
Syntax
You declare an interface with the interface keyword. Its methods have no body, just a signature ending in a semicolon. A class signs the contract with implements:
interface Speaker {
void speak();
}
class Dog implements Speaker {
@Override
public void speak() {
System.out.println("Woof");
}
}
Once Dog implements Speaker, a Dog can be stored in a variable of type Speaker. The code that uses the variable only knows about speak():
Speaker rex = new Dog();
rex.speak();
Woof
Writing code against the interface type, not the concrete class, is the main payoff. A new class that implements Speaker works in the same code without any change to it.
Interface or abstract class
| Abstract class | Interface | |
|---|---|---|
| Models | "is a" | "can do" |
| Instance fields | Yes | No (only constants) |
| Method bodies | Yes, for some methods | Only default, static and private methods |
| Parents a class can have | One | Any number |
A class extends at most one parent class, but it can implement as many interfaces as it needs. That is why Java uses interfaces for capabilities that cut across unrelated classes, such as Comparable and Iterable. To implement several, separate them with commas:
interface Mover {
void move();
}
class Robot implements Speaker, Mover {
@Override
public void speak() { System.out.println("Beep"); }
@Override
public void move() { System.out.println("Rolling"); }
}
A class can combine both keywords, with extends first: class Dog extends Animal implements Speaker.
Details that trip people up
- Interface methods are public. A method declared in an interface is implicitly
public, so the implementing method must be declaredpublictoo. Leaving the modifier off gives a compile error about weaker access privileges. - Implement every method. A concrete class that implements an interface must provide all of its abstract methods. A missing one is a compile error. An abstract class can leave some of them for its subclasses.
@Overrideis optional but worth writing. It asks the compiler to check that the method really matches one from the interface. A typo such asspek()then fails to compile instead of quietly adding a new method.- Default methods. Since Java 8 an interface can carry a method body if you mark it
default. Implementing classes inherit it and may override it:
This still holds no per-object data. A default method can only call the interface's other methods.interface Mover { void move(); default void stop() { System.out.println("Stopped"); } } - You can't instantiate an interface.
new Speaker()doesn't compile on its own. You create an object of a class that implements it, or an anonymous class, or a lambda for an interface with exactly one abstract method:Speaker s = () -> System.out.println("Hi");.
The exercise
The Speaker interface is already declared. The task is to add a Dog class that implements it, with a speak() method that prints Woof, so that mainFunction prints that line.
- Declare the class. Below the interface, write
class Dog implements Speaker. Useimplementshere, notextends, becauseSpeakeris an interface. - Implement the method. Inside
Dog, writepublic void speak()with@Overrideabove it, and print the text withSystem.out.println. The method has to bepublicbecause the interface's method is.
The finished code:
interface Speaker {
void speak();
}
class Dog implements Speaker {
@Override
public void speak() {
System.out.println("Woof");
}
}
class Solution {
public void mainFunction() {
Speaker rex = new Dog();
rex.speak();
}
}
In mainFunction, the variable rex has the type Speaker, while the object is a Dog. Java picks the method from the actual object at run time, so the call prints Woof.
Key takeaways
- An interface lists methods a class promises to provide. It says what, not how.
- Use
implementsfor interfaces andextendsfor a parent class. - A class can implement many interfaces but extend only one class.
- Implementations of interface methods must be
public. - Write code against the interface type so that new implementations plug in unchanged.