All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Back to results for “OOP”
Java › Interfaces & Abstract Classes

What is the fundamental difference between an interface and an abstract class in Java, and when would you choose one over the other?

Beginner

Answer

An abstract class can have both abstract (unimplemented) and concrete (implemented) methods, constructors, instance fields with actual state, and any access modifier on its members, but a class can only extend ONE abstract class (single inheritance); an interface (prior to Java 8) could only declare method signatures with no implementation and public static final constants, but a class can implement MULTIPLE interfaces -- choose an abstract class when you want to share common state and implementation code across closely related subclasses (an 'is-a' relationship with substantial shared behavior), and an interface when you want to define a contract/capability that unrelated classes can implement (a 'can-do' relationship), especially when a class might need to satisfy multiple such contracts simultaneously.
public abstract class Animal {
    protected String name;  // shared state
    public Animal(String name) { this.name = name; }  // constructor
    public abstract void makeSound();  // abstract method, subclasses must implement
    public void sleep() { System.out.println(name + " is sleeping"); }  // shared concrete behavior
}

public interface Swimmer {
    void swim();  // contract, no shared state or constructor
}

public class Duck extends Animal implements Swimmer {  // single inheritance + multiple interface implementation
    public Duck(String name) { super(name); }
    public void makeSound() { System.out.println("Quack"); }
    public void swim() { System.out.println(name + " is swimming"); }
}
Real-world example A Duck class extends the single Animal abstract class (inheriting shared name/sleep() behavior) while also implementing both Swimmer and Flyable interfaces (capabilities not every Animal subclass would need), demonstrating how single-inheritance abstract classes and multiple-implementation interfaces naturally complement each other for different kinds of relationships.

Common follow-ups: Can an interface have constructors or instance fields with actual mutable state, given it can't have instance fields the way an abstract class can?;What changed about interfaces starting in Java 8 that blurred some of this traditional distinction?