Abstraction: Abstract Classes and Interfaces

Site Admin · 11 Sep 2026 · 12 views

Hiding the How

Abstraction means exposing only what an object does, while keeping how it works hidden. In Java you achieve it with abstract classes and interfaces.

Abstract Classes

An abstract class cannot be instantiated. It may contain fully implemented methods plus abstract methods that subclasses must provide.

abstract class Shape {
    abstract double area();   // no body - subclass must implement

    void describe() {         // normal method - inherited as-is
        System.out.println("A geometric shape");
    }
}

class Circle extends Shape {
    double radius;
    Circle(double radius) { this.radius = radius; }

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

Interfaces

An interface declares a contract of what methods a class must implement, without any implementation (except default and static methods).

interface Payable {
    double computeSalary();
}

class Employee implements Payable {
    double hours;
    double rate;

    @Override
    public double computeSalary() { return hours * rate; }
}

Multiple Contracts

A class may implement many interfaces at once, which safely replaces multiple inheritance:

interface Swimmer { void swim(); }
interface Runner  { void run(); }

class Athlete implements Swimmer, Runner {
    public void swim() { System.out.println("Swimming"); }
    public void run()  { System.out.println("Running");  }
}

Abstract Class vs Interface

  • Use an abstract class when subclasses share state and common code.
  • Use an interface when you are declaring capabilities that unrelated classes can implement.

Key Points

  • Abstract classes and interfaces cannot be instantiated directly.
  • Interfaces allow a class to implement many contracts.
  • Both let code depend on a contract instead of a concrete class.
Share this post:

Comments (0)

Please login or register to comment.