Classes and objects

This part builds objects: a class with fields, a constructor and new, instance methods that read them through this, constructors that overload and copy, static fields and methods with the counter they share. Encapsulation follows, with a setter that rejects a value and the exception it throws, then references against objects and == against equals, the contract of equals and hashCode, toString and the methods every class inherits. The part closes with immutable objects and their defensive copies, nested, inner and anonymous classes, enums and composition, a small model in one file, and a bank account capstone whose statement is checked by hand.

4.1 Classes and objects a class, fields, a constructor, new, two objects, references Open 4.2 Instance methods and this methods that read fields, this, getters and setters, a method that returns this Open 4.3 Constructors overloading, this(...), a copy constructor, the default constructor and when it disappears Open 4.4 static fields and methods a counter shared by objects, a static method, a static block, static final constants Open 4.5 Encapsulation and validation private, a setter that rejects a value, the exception it throws, a read-only view Open 4.6 Objects and references a reference is not the object, null, == against equals, NullPointerException read in full Open 4.7 equals and hashCode the contract, a hand-written pair, the HashSet that loses an object without hashCode Open 4.8 toString and the Object methods the default toString, overriding it, getClass, a debug line Open 4.9 Immutable objects final fields, no setters, a defensive copy of an array, String as the model Open 4.10 Nested and inner classes a static nested class, an inner class, an anonymous class, when each is the right one Open 4.11 Enums constants, fields, a constructor, a method, values, valueOf, an enum in a switch Open 4.12 Composition a class built from other objects, delegation, why it beats inheritance here Open 4.13 A small model in one file several classes in one file, one public, a model with a report Open 4.14 Capstone: a bank account accounts, transfers, a rejected withdrawal, a statement, the totals checked by hand Open

Lessons