☕ Java

Abstraction in Java

Abstraction is about showing what something does, not how it does it. You drive a car without knowing how the engine works. You use a method without knowing its internal logic. Java gives you abstract classes and interfaces to define these 'what' contracts.

Abstract Classes — Partial Blueprints

An abstract class is a class that's intentionally incomplete. It can define some methods fully (with bodies), and some methods as abstract — declaring they exist but leaving the implementation to subclasses. You cannot create an object from an abstract class directly. It must be subclassed, and all abstract methods must be implemented. Real-world analogy: A generic "Shape" concept. You know all shapes have an area and a perimeter, but how you calculate them is completely different for a circle vs. a rectangle. So Shape declares these methods abstractly, and each specific shape implements them.
Java
abstract class Shape {
    String color;

    // Abstract method — no body. Every subclass MUST implement this.
    abstract double area();
    abstract double perimeter();

    // Concrete method — has a body, all subclasses inherit it
    public void displayColor() {
        System.out.println("Color: " + color);
    }
}

class Circle extends Shape {
    double radius;

    Circle(double radius, String color) {
        this.radius = radius;
        this.color = color;
    }

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

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

class Rectangle extends Shape {
    double width, height;

    Rectangle(double w, double h, String color) {
        width = w; height = h; this.color = color;
    }

    @Override
    double area() { return width * height; }

    @Override
    double perimeter() { return 2 * (width + height); }
}

// Shape s = new Shape(); // Compile error! Can't instantiate abstract class
Shape circle = new Circle(5.0, "Red");
System.out.println(circle.area());  // 78.539...

Interfaces — Pure Contracts

An interface is a 100% abstract contract. It defines what a class can do, but not how. A class "implements" an interface and must provide concrete implementations for all methods. The real power: a class can implement multiple interfaces. This gives Java a controlled form of multiple inheritance — you get the flexibility without the complexity.
Java
interface Drawable {
    void draw();           // abstract by default — no 'abstract' keyword needed
    void resize(double factor);
}

interface Serializable {
    String serialize();
}

// A class can implement MULTIPLE interfaces
class Canvas implements Drawable, Serializable {
    public void draw() {
        System.out.println("Drawing on canvas...");
    }

    public void resize(double factor) {
        System.out.println("Resizing canvas by factor: " + factor);
    }

    public String serialize() {
        return "{"type": "canvas"}";
    }
}