AccentureObject-Oriented ProgrammingMedium
What is the difference between abstract class and interface in Java?
JavaOOPAbstract ClassInterface
Question
What is the difference between abstract class and interface in Java? Explain with examples.
Answer
Abstract Class:
- Can have both abstract and non-abstract methods
- Can have instance variables
- Can have constructors
- Supports single inheritance
- Can have access modifiers (public, protected, private)
- Can have static and final methods
Interface:
- Can only have abstract methods (before Java 8) or default/static methods (Java 8+)
- Can only have constants (public static final variables)
- Cannot have constructors
- Supports multiple inheritance
- All methods are public by default
- Can have static and default methods (Java 8+)
Example:
// Abstract Class
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
abstract void makeSound();
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Interface
interface Flyable {
void fly();
default void land() {
System.out.println("Landing...");
}
}
Explanation
**Key Differences:**
1. **Inheritance:** A class can extend only one abstract class but can implement multiple interfaces.
2. **Method Implementation:** Abstract classes can have both abstract and concrete methods, while interfaces (before Java 8) could only have abstract methods.
3. **Variables:** Abstract classes can have instance variables, while interfaces can only have constants.
4. **Access Modifiers:** Abstract class methods can have any access modifier, while interface methods are public by default.
5. **Constructor:** Abstract classes can have constructors, interfaces cannot.
**When to Use:**
- Use **abstract class** when you want to share code among closely related classes
- Use **interface** when you want to define a contract that multiple unrelated classes can implement