Advanced Java Class Design
Advanced Java Class Design covers nested and inner classes, enums, interface evolution with default and static methods, and design choices such as composition, immutability, and singletons.
Core rules
- A static nested class is instantiated as
Outer.Nested n = new Outer.Nested();; it has no implicit outer instance. - An inner class requires an outer instance:
outer.new Inner(). Inside an instance method you can usenew Inner(). - Local classes and anonymous classes can capture effectively final local variables.
- Enum constructors are implicitly private; constants are created first, then static initializers run.
values(),valueOf(String),name(), andordinal()are available. An enum can implement interfaces but cannot extend a class. - A
defaultmethod supplies an implementation; if two interfaces provide conflicting defaults, the class must override and may callInterface.super.method(). - An immutable class uses private final fields, no mutators, defensive copies, and a constructor that validates and copies mutable inputs.
Worked example
enum Level { LOW(1), HIGH(3); private final int w; Level(int w){this.w=w;} int w(){return w;} }
Level.values() returns constants in declaration order; Level.valueOf("LOW") returns LOW; Level.LOW.w() returns 1. ordinal() is 0, not the constructor argument.
Traps
new Outer.Inner()fails unlessInneris static; useouter.new Inner().- Enum
toString()can be overridden, butname()cannot. - A local variable captured by a lambda or local class must be final or effectively final.
- A diamond default conflict is a compile error without an explicit override.
- A singleton with a public constructor is not a singleton; an enum singleton is serialization-safe.