⚖️ Interface vs Abstract Class in Java
| Feature | Interface | Abstract Class |
|---|---|---|
| Purpose | Define a contract (what a class must do) | Provide partial implementation (what & some how) |
| Methods (Java 7) | All methods are abstract (no body) |
Can have both abstract and non-abstract methods |
| Methods (Java 8+) | Can have default, static methods with body |
Still supports both, but not static interfaces |
| Access Modifiers | Methods are public by default |
Can be private, protected, or public
|
| Constructors | ❌ Not allowed | ✅ Allowed |
| Variables |
public static final by default (constants only) |
Can have instance variables |
| Multiple Inheritance | ✅ Supported (a class can implement multiple interfaces) | ❌ Not supported (only single inheritance) |
| Inheritance Keyword | implements |
extends |
| Use Case | When you want to define a capability | When you want to define a base class with behavior |
| Abstract Keyword | Not required for methods or interface itself | Must use abstract keyword for class and methods |
| Performance | Slightly faster, less overhead | Slightly more overhead due to partial implementation |
🔧 Example: Interface
interface Flyable {
void fly();
}
class Bird implements Flyable {
public void fly() {
System.out.println("Bird is flying");
}
}
🛠️ Example: Abstract Class
🧠 When to Use What?
| If You Want To... | Use |
|---|---|
| Define pure behavior contract | Interface |
| Provide base functionality + force override | Abstract Class |
| Achieve multiple inheritance | Interface |
| Define constant values | Interface |
✅ Summary
- Use Interface when you're defining what to do (API or contract).
- Use Abstract Class when you're defining what to do and partially how to do it.