Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Advanced Java Class Design

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

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 use new 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(), and ordinal() are available. An enum can implement interfaces but cannot extend a class.
  • A default method supplies an implementation; if two interfaces provide conflicting defaults, the class must override and may call Interface.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 unless Inner is static; use outer.new Inner().
  • Enum toString() can be overridden, but name() 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.