Sobes.tech
Middle

When should you use an interface, and when an abstract class?

sobes.tech AI

Answer from AI

We use an abstract class to create basic functionality and common state that subclasses can inherit. It is suitable when there are common methods with implementation and methods that need to be overridden. An abstract class can have fields and constructors.

// Abstract class
abstract class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    abstract void makeSound(); // Abstract method

    void eat() { // Method with implementation
        System.out.println(name + " is eating.");
    }
}

We use an interface to define a contract describing a set of methods that must be implemented by classes. It is suitable for achieving multiple behaviors (multiple inheritance of functionality). An interface cannot have state (instance fields, except constants) and constructors (before Java 8).

// Interface
interface Flyable {
    void fly(); // Abstract method
}

Summary table of differences:

Attribute Abstract Class Interface
Member types Fields, abstract and concrete methods, constructors Constants, abstract methods (by default), static and default methods (from Java 8)
Method implementation Can have methods with implementation Only abstract methods before Java 8, with Java 8 - static and default
State Can have state (fields) Cannot have state (instance fields)
Inheritance Single inheritance Multiple implementation
Usage "is-a" - base type "has-a" - behavior contract
When should you use an interface, and when an… - sobes.tech