🏗️ Classes & Objects
14 Java concepts, each explained step by step with real code, a common trap and practice questions.
- Class vs objectA class is a blueprint; objects are instances created with new.
- Fields & stateInstance fields hold each object's state.
- ConstructorsSame name as class, no return type, the implicit default constructor and when it disappears.
- The this keywordRefers to the current object; disambiguates fields from parameters.
- Constructor chaining with this()Calling another constructor; must be the first statement (before Java 25 flexible bodies).
- Access modifierspublic, protected, package-private (default), private.
- EncapsulationPrivate fields, controlled access through methods, validating invariants.
- Static fields & methodsOne copy per class shared by all instances.
- Initializer blocks & init orderStatic blocks once at class init; instance blocks before the constructor body.
- References, aliasing & nullTwo variables can point to one object; NullPointerException and helpful NPE messages.
- Object lifetime & garbage collectionUnreachable objects are collected automatically; no destructors; finalize is deprecated.
- toString()Default ClassName@hash and overriding it for readable output.
- Packages & importsPackage naming, import, static import, java.lang is automatic, name clashes.
- Immutable classesfinal class, private final fields, no setters, defensive copies.