Interfaces
Pure abstraction with interface keyword
Interview Relevant: Interface vs Abstract class
6 min read
Interfaces
Interfaces define contracts. Classes can implement multiple interfaces.
Code Examples
Multiple inheritance via interfaces
java
1
2interface Flyable {
3 void fly();
4}
5
6interface Swimmable {
7 void swim();
8}
9
10class Duck implements Flyable, Swimmable {
11 public void fly() {}
12 public void swim() {}
13}
14 Use Cases
- Multiple inheritance
- Strategy pattern
- Dependency injection
Common Mistakes to Avoid
- Using interfaces for state
- Forgetting methods are public by default