Java Interfaces
An interface is a list of method headings with no bodies. A class that implements an interface writes a body for each listed method.
A class implements an interface
The Animal interface lists two methods. Dog writes a body for each one.
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.sleep();
}
}
interface Animal {
void sound();
void sleep();
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof");
}
public void sleep() {
System.out.println("Zzz");
}
}One class implements two interfaces
Duck implements Flyer and Swimmer. The class writes a body for the method in each interface.
public class Main {
public static void main(String[] args) {
Duck duck = new Duck();
duck.fly();
duck.swim();
}
}
interface Flyer {
void fly();
}
interface Swimmer {
void swim();
}
class Duck implements Flyer, Swimmer {
public void fly() {
System.out.println("The duck flies");
}
public void swim() {
System.out.println("The duck swims");
}
}An interface type holds the object
The variable has the interface type Greeter. It holds a Robot object.
public class Main {
public static void main(String[] args) {
Greeter greeter = new Robot();
greeter.greet();
}
}
interface Greeter {
void greet();
}
class Robot implements Greeter {
public void greet() {
System.out.println("Hello from the robot");
}
}Example
public class Main {
public static void main(String[] args) {
Card card = new Card();
card.pay(25);
}
}
interface Payment {
void pay(int amount);
}
class Card implements Payment {
public void pay(int amount) {
System.out.println("Paid " + amount + " by card");
}
}Key points
- The interface keyword starts an interface.
- A method in an interface has a heading and no body.
- A class uses the implements keyword to take on an interface.
- The class must write a body for each method in the interface.
- A method that implements an interface is marked public.
- A class can implement more than one interface.
In this example, the Payment interface lists one method named pay. The method takes an int value. Card implements Payment and writes the body of pay. The call passes 25, and the body prints the paid line.
Note
An interface names what a class can do, and the class supplies how it is done.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does a class promise when it implements an interface?