Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    The Whole Story

    The whole module retold as one story — no new facts, a fast revision of Classes, Objects and Memory.

    Extra: Revision3 min read

    Parallel arrays break the moment one of them is sorted or grows, so Java lets you invent your own types. A class is a blueprint and an object is a house built from it, each with its own fields (Ch 1). A constructor, named like the class and with no return type, hands over a house that's ready to live in, with this separating the object's field from a parameter of the same name, and this(...) reusing another constructor (Ch 2). What belongs to each house is instance; what belongs to the whole street — a shared counter, a utility like Math.max — is static, which is why a static method has no this (Ch 3).

    Houses live in the city — the heap — and variables only hold address cards: references. Copy the card and two names point to one house (aliasing); pass a card to a method and it gets a copy, so it can repaint the house but never move your card (pass-by-value); a blank card is null, and following it throws a NullPointerException; and a house nobody holds a card for is cleared away by the garbage collector (Ch 4). final fixes the card, not the house; truly unchangeable houses are immutable classes, safe to share anywhere (Ch 5).

    The most important immutable class is String: printed badges that never change, with literals shared from the String pool — which is exactly why == sometimes seems to work and why you must always use .equals (Ch 6). When you need to build text, you use a whiteboard, StringBuilder, turning an O(n²) loop of += into O(n) (Ch 7). Because collections only accept objects, every primitive has a wrapper box — Integer, Character — packed and unpacked automatically (autoboxing), with two traps: the −128..127 Integer cache that fools ==, and unboxing null (Ch 8). Identity (==) and equality (equals) are different questions, and your own classes answer the second one wrongly until you teach them — along with a readable toString (Ch 9). Finally, classes are grouped into packages that mirror folders, pulled in with imports (Ch 10).

    Next, Object-Oriented Programming uses all of this to build the four pillars of object-oriented programming — and to write equals and hashCode properly.