पाठ 6 / 25

Abstraction, Abstract Classes and Interfaces

Distinguish abstraction from encapsulation and choose between abstract classes and interfaces.

Showing what, hiding how

Abstraction means presenting the essential features of something while hiding unnecessary detail: you call list.sort() without knowing which sorting algorithm runs. Encapsulation is the mechanism that hides data; abstraction is the design that decides what to expose. In Java, two tools express abstractions. An abstract class (abstract class Shape) cannot be instantiated; it may contain fields, constructors, concrete methods and abstract methods (declared without a body) that subclasses must implement. Use it when related classes share state and code. An interface defines a contract of methods a class promises to provide; a class can implement many interfaces but extend only one class. Since Java 8, interfaces can also have default and static methods, and since Java 9 private helper methods, but they still cannot hold instance state. Prefer interfaces for capabilities (Comparable, Runnable, PaymentGateway) and abstract classes for a family with shared implementation.

An interface and an abstract class working together

The interface is the contract; the abstract class shares common code.

public interface Shape {
    double area();
    default String describe() {                     // default method (Java 8+)
        return getClass().getSimpleName() + " with area " + area();
    }
}

public abstract class Polygon implements Shape {
    protected final double[] sides;

    protected Polygon(double... sides) { this.sides = sides.clone(); }

    public double perimeter() {                     // shared implementation
        double p = 0;
        for (double s : sides) p += s;
        return p;
    }
}

public final class Square extends Polygon {
    public Square(double side) { super(side, side, side, side); }
    @Override public double area() { return sides[0] * sides[0]; }
}

public final class Circle implements Shape {
    private final double r;
    public Circle(double r) { this.r = r; }
    @Override public double area() { return Math.PI * r * r; }
}

Classic exam question

"Differentiate between abstract class and interface": abstract classes can have state, constructors and any access modifiers, and support single inheritance; interfaces define contracts, allow multiple implementation and (in modern Java) default methods without instance state.

त्वरित जाँच: Which is true about Java interfaces and abstract classes?

  • A class can implement several interfaces but extend only one class
  • A class can extend several abstract classes
  • Interfaces can hold instance fields
  • Abstract classes can be instantiated with new
Answer

A class can implement several interfaces but extend only one class — Java supports single class inheritance and multiple interface implementation.