Java ยท Chapter 28 of 42

Java Abstraction

Abstraction hides complex implementation details and exposes only the essential features of an object. In Java, abstraction is achieved using abstract classes and interfaces.

An abstract class can have both abstract methods (no body, to be implemented by subclasses) and concrete methods, and cannot be instantiated directly.

Syntax
abstract class C {
  abstract void method();
}

Abstract classes

Declared with the `abstract` keyword, abstract classes can contain abstract methods (declared but not implemented) as well as regular methods with implementations.

Why use abstraction?

Abstraction lets you define a common contract for related classes while letting each subclass provide its own specific implementation details.

Example 1 (java)
abstract class Shape {
  abstract double area();
}
class Circle extends Shape {
  double radius = 2;
  double area() { return Math.PI * radius * radius; }
}
public class Main {
  public static void main(String[] args) {
    Shape s = new Circle();
    System.out.println(s.area());
  }
}
Output
12.566370614359172

Shape defines the abstract area() method, and Circle provides its concrete implementation.

Key points

  • Abstract classes cannot be instantiated directly.
  • Abstract methods have no body; subclasses must implement them.
  • Abstract classes can mix abstract and concrete methods.
  • Abstraction defines a contract while hiding implementation details.
๐Ÿ’ก Note: Use an abstract class when related classes share some common code, not just a common contract.

๐Ÿ“ Quick Quiz

1. Can you instantiate an abstract class directly?

2. What must a subclass do with an abstract method?

3. Can an abstract class have concrete methods?