CKTIS / Java
Java object model
Java object model: Java’s object model combines single class inheritance, multiple interfaces, and composition; a static nested class has no enclosing instance, while an inner class does.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
object modelJava’s object model combines single class inheritance, multiple interfaces, and composition; a static nested class has no enclosing instance, while an inner class does.
Prefer composition for replaceable behavior, an interface for a contract, and a sealed hierarchy for a closed set of variants; defensive copies protect object boundaries.
An inner class can retain its outer object, while local and anonymous classes capture only final or effectively final local variables; shallow immutability shares nested elements, whereas deep immutability requires copying or freezing the mutable object graph.
Create an inner instance with outer.new Inner(); an anonymous class has no named constructor, and a correct equals requires a consistent hashCode for maps and sets.
Stdout static, outer, local, and anonymous distinguishes four class forms; shallow=[A, B], deep=[A], and outer-sizes=1/1 prove defensive copying and the shallow-versus-deeper-copy distinction.
Examples
import java.util.ArrayList;
import java.util.List;
public class Main {
private final String name;
Main(String name) { this.name = name; }
static final class Nested {
String value() { return "static"; }
}
final class Inner {
String owner() { return name; }
}
static final class Box {
private final List<List<String>> shallow;
private final List<List<String>> deep;
Box(List<List<String>> source) {
shallow = List.copyOf(source);
deep = source.stream().map(List::copyOf).toList();
}
}
public static void main(String[] args) {
var outer = new Main("outer");
var inner = outer.new Inner();
class Local { String value() { return "local"; } }
Runnable anonymous = new Runnable() {
@Override public void run() { System.out.println("anonymous"); }
};
System.out.println(new Nested().value());
System.out.println(inner.owner());
System.out.println(new Local().value());
anonymous.run();
var mutable = new ArrayList<>(List.of("A"));
var source = new ArrayList<List<String>>();
source.add(mutable);
var box = new Box(source);
mutable.add("B");
source.add(List.of("C"));
System.out.println("shallow=" + box.shallow.get(0));
System.out.println("deep=" + box.deep.get(0));
System.out.println("outer-sizes=" + box.shallow.size() + "/" + box.deep.size());
}
}
Result
static outer local anonymous shallow=[A, B] deep=[A] outer-sizes=1/1
Stdout static, outer, local, and anonymous distinguishes four class forms; shallow=[A, B], deep=[A], and outer-sizes=1/1 prove defensive copying and the shallow-versus-deeper-copy distinction.