interface in Java
- by utk
What is an Interface in Java?
An interface in Java is a contract that defines what a class must do, but not how it does
it.
Think of it as a blueprint:
• It declares methods but does not implement them (until Java 8).
• A class that implements an interface must provide concrete implementations for
all its abstract methods.
🔹 Why Use Interfaces?
Achieve abstraction
Support multiple inheritance (Java doesn't allow multiple class inheritance)
Promote loose coupling and better testability
Enable polymorphism (use different implementations interchangeably)
🔹 Basic Interface Example
java
CopyEdit
interface Animal {
void makeSound(); // abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof!");
}
}