Course contentsShow
← Java
Lesson 527 of 2,87012. Abstract Classes and InterfacesFree lesson

State and Constructors: Abstract Classes Can Have Both

How abstract classes can maintain instance fields and constructors, unlike interfaces, for shared state across subclasses.

State and Constructors: Abstract Classes Can Have Both

You'll learn: How abstract classes differ from interfaces by supporting instance fields and constructors for shared state management.

The Fundamental Difference

While interfaces define contracts (what a class must do), abstract classes can also manage internal state (data) and initialization logic. Abstract classes can declare instance fields and constructors, features that interfaces traditionally cannot provide in the same way. This makes abstract classes ideal when your subclasses need to share common data or setup behavior.

Instance Fields in Abstract Classes

Abstract classes can maintain instance variables that all subclasses inherit:

public abstract class Animal {
    protected String name;  // Shared state
    protected int age;      // All animals have age
    
    public abstract void makeSound();
}

Every subclass of Animal automatically has name and age fields without redefining them.

Constructors for Initialization

Abstract classes can have constructors to initialize this shared state, even though you can't instantiate the abstract class directly:

public abstract class Animal {
    protected String name;
    protected int age;
    
    // Constructor ensures every Animal has a name
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public abstract void makeSound();
}

public class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);  // Must call parent constructor
    }
    
    public void makeSound() {
        System.out.println(name + " barks!");
    }
}

When you create a Dog, its constructor invokes Animal's constructor to properly initialize the inherited state.

Why This Matters

Interfaces cannot enforce shared state or initialization patterns (prior to recent Java versions with restrictions). Abstract classes give you a blueprint with both behavior contracts (abstract methods) and shared data infrastructure (fields + constructors).

Key Takeaway: Abstract classes can declare instance fields and constructors to manage shared state and initialization logic across all subclasses—capabilities interfaces don't provide in the same direct way.