Abstract Classes

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • An Abstract Class is a class declared with the abstract keyword.
  • It cannot be instantiated (new AbstractClass() is illegal).
  • It can contain a mix of both abstract methods (no body) and concrete methods (with bodies).
  • It is used when you want to share common code among closely related classes but enforce that child classes implement specific behaviors.

Concept

Abstract classes act as a base or template. They are perfect for situations where subclasses share a lot of identical code, but still have unique behaviors that must be forced upon them.

When to use Abstract Classes vs Interfaces

  • Use an Abstract Class when classes share an IS-A identity and share a lot of core logic or state (fields).
  • Use an Interface when classes share a CAN-DO behavior (like Flyable), especially if the classes are otherwise completely unrelated (e.g., a Bird and an Airplane can both fly, but they shouldn’t share an abstract parent class).

Examples

abstract class Shape {
    String color;
    
    public Shape(String color) {
        this.color = color;
    }
    
    // Abstract method: Forces child to implement
    abstract double calculateArea();
    
    // Concrete method: Code reused by all children
    public void printColor() {
        System.out.println("This shape is " + color);
    }
}

class Circle extends Shape {
    double radius;
    
    public Circle(String color, double radius) {
        super(color); // Must call parent constructor
        this.radius = radius;
    }
    
    @Override
    double calculateArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape c = new Circle("Red", 5.0);
        c.printColor(); // Inherited logic
        System.out.println(c.calculateArea()); // Specific logic
    }
}

Interview Questions

Q: Can an abstract class be final?
A: No. This is a compile-time error. The final keyword prevents a class from being inherited. The abstract keyword requires a class to be inherited (otherwise its abstract methods can never be implemented). They are exact opposites.

Q: Can an abstract class have no abstract methods?
A: Yes. You can declare a class abstract even if every single method inside it has a body. This is a design choice used simply to prevent other developers from instantiating the class directly.