An interface is like a contract. It says, "If you use me, you must do these things." It defines what should be done, not how to do it.
Think of a TV remote. It has buttons: power, volume, channel, etc. Every brand has a remote. But the buttons are always there. This is like an interface.
The remote says: "You must give me a turnOn()
and changeChannel()
function."
It doesn't care how the TV turns on. Each brand does it in its own way.
interface Animal {
void makeSound();
void eat();
}
This says: "Any animal must make a sound and eat."
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof!");
}
public void eat() {
System.out.println("Dog eats bones.");
}
}
The Dog
class agrees to the contract. It gives details for makeSound()
and
eat()
.
You shop online. You can pay with credit card, PayPal, or a gift card. Each one works differently. But they all have
one job: pay()
.
interface PaymentMethod {
void pay(double amount);
}
class CreditCard implements PaymentMethod {
public void pay(double amount) {
System.out.println("Paid with credit card: $" + amount);
}
}
class PayPal implements PaymentMethod {
public void pay(double amount) {
System.out.println("Paid with PayPal: $" + amount);
}
}
In Java 8 and later, interfaces can have default
methods too.
interface Greeting {
default void sayHello() {
System.out.println("Hello!");
}
}
implements
keyword