Abstract class
An abstract class is a class marked with the abstract keyword that cannot be instantiated directly. It exists to be extended by subclasses. It can declare abstract methods (no body) that subclasses must implement, and also hold concrete methods and instance fields.
Example
public abstract class Animal {
protected final String name;
public Animal(String name) { this.name = name; }
public abstract String sound(); // subclasses must implement
public void introduce() { // shared concrete behaviour
System.out.println(name + " says " + sound());
}
}
public class Dog extends Animal {
public Dog(String name) { super(name); }
@Override public String sound() { return "Woof"; }
}
Abstract class vs interface
| Abstract class | Interface | |
|---|---|---|
| Instance fields | Yes | No (only constants) |
| Constructor | Yes | No |
| Multiple inheritance | No (extends one) | Yes (implements many) |
| Use when | Sharing code among related classes | Defining a capability |
Modern guidance
Prefer interfaces with default methods where possible — they're more flexible. Use abstract classes when you genuinely need to share state (instance fields) or have a common constructor across subclasses.