Back to course

OOP Pillar 4: Abstraction using Abstract Classes

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 24: OOP Pillar 4: Abstraction using Abstract Classes

Abstraction means showing only essential information to the user and hiding the complex implementation details. It focuses on what an object does rather than how it does it.

1. Abstract Classes

  • An abstract class is declared using the abstract keyword.
  • It may contain both implemented (concrete) methods and unimplemented (abstract) methods.
  • Crucially: You cannot create objects (instances) of an abstract class.

2. Abstract Methods

  • An abstract method is a method declared without an implementation (no body, ends with a semicolon).
  • Any class containing one or more abstract methods must be declared abstract.
  • Subclasses must provide implementations for all inherited abstract methods, or they must also be declared abstract.

Example

java public abstract class Shape { // Abstract class String color;

// Concrete method (implemented)
public void printColor() {
    System.out.println("Color: " + color);
}

// Abstract method (no body) - forces subclasses to implement this
public abstract double calculateArea(); 

}

// Subclass must implement the abstract method public class Circle extends Shape { private double radius = 5.0;

@Override
public double calculateArea() {
    return Math.PI * radius * radius;
}

}

// Usage: // Shape s = new Shape(); // ERROR! Cannot instantiate abstract class Shape c = new Circle(); // OK (Polymorphism) double area = c.calculateArea();

Abstract classes are perfect for sharing common code while forcing specific implementations for critical behaviors across related subclasses.