Java.Core.What is the difference between an abstract class and an interface? When should you use an abstract class and when should you use an interface?

Difference Between an Abstract Class and an Interface in Java

FeatureAbstract ClassInterface
Inheritance TypeSupports single inheritanceSupports multiple inheritance
MethodsCan have both abstract and concrete methodsCan have abstract, default, and static methods (default and static since Java 8)
Access ModifiersMethods can have any access modifier (private, protected, public)Methods are implicitly public abstract unless default or static
FieldsCan have instance variables and static fieldsOnly public static final (constants)
ConstructorsCan have constructorsCannot have constructors
State MaintenanceCan maintain state (instance variables)Cannot maintain state (only constants)
Use CaseWhen you want to provide a base class with shared behaviorWhen you want to define a contract that multiple classes can implement

When to Use an Abstract Class vs. an Interface?

Use an Abstract Class When:

  1. You need to share code among related classes.
  2. You need constructors or instance variables.
  3. You want to provide a base implementation that subclasses can override or extend.
  4. You expect future changes in method implementations without affecting all subclasses.

✅ Example:

abstract class Animal {
    String name;

    Animal(String name) { // Constructor allowed
        this.name = name;
    }

    void sleep() { // Concrete method
        System.out.println(name + " is sleeping.");
    }

    abstract void makeSound(); // Abstract method (must be implemented by subclasses)
}

Use an Interface When:

  1. You need to define a contract that unrelated classes can implement.
  2. You require multiple inheritance (since Java allows multiple interfaces but not multiple abstract classes).
  3. You want to achieve pure abstraction (before Java 8).
  4. You are working with API design, where different classes should follow the same behavior.

✅ Example:

interface Flyable {
    void fly(); // Implicitly public and abstract
}

class Bird implements Flyable {
    public void fly() {
        System.out.println("Bird is flying.");
    }
}

Final Thoughts

  • If you need default behavior, shared fields, and constructors → Use an abstract class.
  • If you need multiple inheritance, a strict contract, and full abstraction → Use an interface.
  • Java 8+ blurs the distinction since interfaces now support default and static methods.
This entry was posted in Без рубрики. Bookmark the permalink.