Interfaces
An interface in Java is like a pure abstraction.
Itโs a contract that says: โAny class that implements me promises to provide these methods.โ
Key difference from abstract class:
An interface has no fields (except static final constants).
All methods are abstract by default (until Java 8 โ newer Java allows default and static methods too).
A class can implement multiple interfaces, but can extend only one class.
Why use interfaces?
To design common behaviors that unrelated classes can share.
To support multiple inheritance of type (Java does not support multiple inheritance of classes, but you can implement many interfaces).
To keep your code flexible and testable โ itโs easy to swap implementations.
Declaring an interface:
makeSound()
and eat()
have no body.
Any class that implements Animal
must define both methods.
Implementing an interface:
Key points:
Use implements
to connect class to interface.
Use @Override
for each method.
The compiler checks that you implemented all methods.
In real projects, you often combine both.
Example:
How this works:
Animal
defines common blueprint for all animals.
Pet
defines extra behavior for pets.
Dog
combines both โ itโs an Animal
that is also a Pet
.