R
Rishtaara
Java Fundamentals
Lesson 21 of 36Article16 min

Inner Classes & Abstraction

Inner class lives inside outer class. Useful for helpers tightly tied to outer class.

Inner Classes — class inside a class

Inner class lives inside outer class. Useful for helpers tightly tied to outer class.

Static nested class does not need outer instance. Non-static inner class needs outer object.

Real-life example: Inner class is a pocket inside a jacket — belongs to that jacket, not worn alone on the street.

Inner class
class Outer {
    private int x = 10;

    class Inner {
        void show() {
            System.out.println("x = " + x);
        }
    }
}

Outer o = new Outer();
Outer.Inner inner = o.new Inner();
inner.show();

Abstraction — abstract classes

abstract class cannot be instantiated. It may have abstract methods (no body) and concrete methods.

Subclass must implement all abstract methods unless subclass is also abstract.

Real-life example: "Vehicle" abstract — no single vehicle exists, but Car and Bike fill in startEngine() their own way.

Abstract class
abstract class Vehicle {
    abstract void start();

    void stop() {
        System.out.println("Stopped");
    }
}

class Bike extends Vehicle {
    @Override
    void start() {
        System.out.println("Kick start");
    }
}