What is Interface in Java: Definition and Usage Explained
interface is a blueprint for classes that defines a set of abstract methods without implementations. It allows different classes to share common behavior by implementing the interface's methods.How It Works
An interface in Java works like a contract or a promise that a class agrees to follow. Imagine you have a remote control interface that says any device with this remote must have buttons to turn on, turn off, and change channels. The interface only lists these actions but does not say how to do them.
When a class implements this interface, it must provide the actual code for these actions. This way, different devices like TVs or radios can have their own ways to turn on or change channels, but they all follow the same set of rules defined by the interface.
This helps organize code and allows different classes to work together through a common set of methods, even if their internal workings are different.
Example
This example shows an interface Animal with a method sound(). Two classes, Dog and Cat, implement this interface and provide their own sounds.
interface Animal { void sound(); } class Dog implements Animal { public void sound() { System.out.println("Dog says: Woof Woof"); } } class Cat implements Animal { public void sound() { System.out.println("Cat says: Meow Meow"); } } public class Main { public static void main(String[] args) { Animal dog = new Dog(); Animal cat = new Cat(); dog.sound(); cat.sound(); } }
When to Use
Use interfaces when you want to define a common set of actions that different classes should follow, but each class can have its own way of doing them. This is useful in large programs where many objects need to interact but are built differently.
For example, in a payment system, you might have an interface PaymentMethod with a method pay(). Different classes like CreditCard, PayPal, or BankTransfer implement this interface to handle payments in their own way.
Interfaces also help with organizing code, making it easier to change or add new features without breaking existing code.
Key Points
- An interface only declares methods without implementing them.
- Classes implement interfaces to provide method bodies.
- Interfaces help achieve abstraction and multiple inheritance in Java.
- They define a contract that classes must follow.
- Interfaces improve code flexibility and reusability.