Lesson 25: Abstraction using Interfaces
An Interface is another way to achieve 100% abstraction in Java. It is a blueprint of a class that defines a contract: any class implementing the interface must define the methods declared within it.
1. Key Characteristics of Interfaces
- Defined using the
interfacekeyword. - A class uses the
implementskeyword to adopt an interface. - Interfaces support multiple inheritance (a class can implement multiple interfaces).
- Before Java 8, all methods in an interface were implicitly
publicandabstract.
java public interface Swimmer { // Interface // All methods are public abstract by default void swim(); void dive(int depth); }
public class Dolphin implements Swimmer { @Override public void swim() { System.out.println("Dolphin swims gracefully."); }
@Override
public void dive(int depth) {
System.out.println("Diving to " + depth + " meters.");
}
}
2. Default Methods (Java 8+)
Before Java 8, if you added a new method to an interface, every implementing class would break. Default methods solve this by allowing methods with a body in the interface itself.
java public interface Swimmer { void swim();
// Default method: provides a default implementation
default void checkStatus() {
System.out.println("Swimmer status: OK");
}
}
// Dolphin does not need to implement checkStatus() unless it wants to override it.
3. Interfaces vs. Abstract Classes
| Feature | Interface | Abstract Class |
|---|---|---|
| Inheritance | Multiple (implements) | Single (extends) |
| Constructors | Cannot have constructors | Can have constructors |
| Fields | Only public static final | Can have any type of field |
| Abstraction Level | 100% (mostly) | 0% to 100% |
Use Case: Use Interfaces when defining a capability or contract (e.g., Runnable, Comparable). Use Abstract Classes when providing a base implementation for a closely related set of classes (e.g., Shape, Employee).