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

Fields and Instance Variables in Abstract Classes

Using fields in abstract classes to store state shared by all subclasses, just like in concrete classes.

Fields and Instance Variables in Abstract Classes

What you'll learn: How to use fields in abstract classes to store state that's shared across all subclasses, just like you would in regular concrete classes.

The Core Idea

Abstract classes can have fields (instance variables) just like any concrete class. These fields store state that every subclass will inherit and share. Even though you can't directly instantiate an abstract class, its fields are fully initialized when a subclass object is created, providing common data to all descendants.

Think of it this way: an abstract class is like a blueprint that includes storage compartments. Even though you can't build the blueprint itself, every building made from it will have those same storage spaces.

Using Fields in Abstract Classes

Fields in abstract classes work exactly as they do in concrete classes:

public abstract class Vehicle {
    // Instance fields — every Vehicle subclass will have these
    protected String brand;
    protected int yearManufactured;
    private boolean isRunning;

    public Vehicle(String brand, int year) {
        this.brand = brand;
        this.yearManufactured = year;
        this.isRunning = false;
    }

    public void startEngine() {
        isRunning = true;
    }

    // Abstract method — subclasses must implement
    public abstract void move();
}

public class Car extends Vehicle {
    public Car(String brand, int year) {
        super(brand, year); // Initializes inherited fields
    }

    @Override
    public void move() {
        System.out.println(brand + " car is driving"); // Uses inherited field
    }
}

Every Car object has brand, yearManufactured, and isRunning fields, initialized through the abstract class's constructor.

When to Use Fields in Abstract Classes

Use fields in abstract classes when all subclasses naturally share common state. This eliminates duplicate field declarations and ensures consistent data structure across your hierarchy.

Key Takeaway: Abstract classes can declare and initialize fields just like concrete classes—these fields become part of every subclass instance, providing shared state across your inheritance hierarchy.