Nested Classes Inner Static Distinction

An inner class carries an outer instance and reads its private fields; a static nested class is a plain top-level class parked inside another one.

JavaData Integrity

Code

snippet
public class OuterMachine {

    private int gear = 1;

    // inner class:绑定外围实例,可直读其私有字段
    class InstrumentPanel {
        String readout() {
            return "gear=" + gear + " via " + OuterMachine.this.gear;
        }
    }

    // static nested class:不需要外围实例,只能经引用访问实例成员
    static class SerialNumber {
        private final String value;

        SerialNumber(String value) {
            this.value = value;
        }

        String value() {
            return value;
        }
    }

    public static void main(String[] args) {
        OuterMachine machine = new OuterMachine();

        // inner 类必须先有外围实例:outerInstance.new Inner()
        OuterMachine.InstrumentPanel panel = machine.new InstrumentPanel();
        System.out.println("panel: " + panel.readout());

        // static nested 直接 new,与顶层类一致
        OuterMachine.SerialNumber serial = new OuterMachine.SerialNumber("SN-001");
        System.out.println("serial: " + serial.value());

        // 换一台机器,inner 读到的是那台机器的 gear
        OuterMachine other = new OuterMachine();
        other.gear = 4;
        System.out.println("other: " + other.new InstrumentPanel().readout());
    }
}

What the code does

Nested Classes Inner Static Distinction is built around the classes OuterMachine, InstrumentPanel and SerialNumber and the function main.

Watch out for

  • Nothing needs adding to the project before it runs.

Using it

The signature you will reach for first is public static void main(String[] args)

Look for the panel:, serial:, other: prefixes during the file’s run; they match each line of output to the step that emitted it.

The key statements, annotated

return "gear=" + gear + " via " + OuterMachine.this.gear;

Interactive Tools for This Topic

FAQ

What does Nested Classes Inner Static Distinction print when run?
The script runs standalone; its 3 labeled outputs include `panel:`, `serial:`, `other:`.