Java Abstract Class — Summary

Definition

  • A class declared with the abstract keyword.
  • Cannot be instantiated directly.
  • Can contain abstract methods (no body) and concrete methods (with body).

Key Points

  1. Purpose

    • To provide a base class with common fields/methods while enforcing subclasses to implement certain methods.
  2. Abstract Methods

    • Declared without a body:
      abstract void draw();
    • Must be implemented by the first concrete subclass.
  3. Concrete Methods

    • Abstract classes can also have fully implemented methods.
  4. Constructors & Fields

    • Can have constructors, instance variables, and static members.
  5. Inheritance Rules

    • A subclass must either:
      • Implement all abstract methods, or
      • Be declared abstract itself.
    • Supports single inheritance (unlike interfaces which can be multiple).
  6. Difference from Interface

    • Abstract class: can have state (fields), constructors, and both abstract & concrete methods.
    • Interface: cannot have instance fields (only constants), but can have default/static methods (Java 8+).

Example

abstract class Shape {    
    String color;
    // Abstract method
    abstract double area();
    // Concrete method
    void setColor(String color) {
        this.color = color;
    }
}

class Circle extends Shape {
    double radius;
    Circle(double radius) {
        this.radius = radius;
    }
    
    @Override
double area() {
        return Math.PI * radius * radius;
    }
}

public
class Main {
    public static void main(String[] args) {
    Shape s = new Circle(5);
    s.setColor("Red");
    System.out.println("Area: " + s.area());
    }
}

When to use:

  • You have a base class with shared code but also methods that must be implemented by subclasses.
← Back to Learning Journey