Abstract class is a class that canβt be instantiated and may contain abstract methods (without implementation). Itβs used as a base for other classes to inherit and implement common behavior.
Example
abstract class Animal {
abstract void makeSound();
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
Animal animal = new Dog();
dog.makeSound(); // "Bark"
dog.eat(); // "Eating..."
Features
- Can have abstract and concrete methods.
- Can have constructors, fields and static methods.
- Canβt be instantiated directly.
- Child class must implement all abstract methods.
Comparison
Abstract Class vs Interface
Feature | Abstract Class | Interface |
---|---|---|
Method Types | Abstract + Concrete | Abstract (default), default, static |
Instantiation | β | β |
Constructors | β | β |
Multiple Inheritance | β | β |
Access Modifiers | Any | public only (before Java 8) |
Fields | Any | public static final only |
Tip
Use abstract clas when you want to share code among related classes.
Use an interface when you want to define a contract without shared implementation.
Parent: _OOP Advanced Tools