Layers of Logic

Phase VIII

Identity and Contracts

Teaching Java what "the same" means, and what happens when you get it wrong.

5 sections98 min of reading21 exercises

The last phase of Layers of Logic Phase 1, and the one everything has been aimed at. You will find out what Scanner really is, build a class that genuinely cannot change, and then write equals and hashCode, the two methods that decide whether your objects can be found again. Get them wrong and data disappears with no exception and no warning. You will make that happen on purpose, so that when HashMap arrives in Phase X you already know what it is asking of you.

When you finish this phase you can

  • Explain the three layers in new BufferedReader(new InputStreamReader(System.in))
  • Say why buffering turns a million system calls into a hundred
  • Build a genuinely immutable class, including the step that final does not cover
  • Write equals and hashCode correctly, and state the contract between them
  • Demonstrate a HashMap losing a value, and explain exactly where it went
  • Choose an enum over int or String constants, and say what the compiler gains
  • Define a functional interface, and explain why a lambda needs one
  1. 8.1Java I/O: Streams, Scanner, BufferedReaderYou have been using `Scanner` since Phase I without being told what it is. Here is the machine underneath it, and why reading one byte at a time is a thousand times slower than it needs to be.Stream (I/O)BufferingCore19 min4 exercises
  2. 8.2Immutable ClassesAn object that can never change is safe to share with anyone, forever, with no locks and no copies. Getting there takes four steps, and `final` is only the first one.ImmutabilityCore17 min4 exercises
  3. 8.3The Object Class: `equals`, `hashCode`, `toString`Every class you have ever written already extends one class you never mentioned. Three of its methods decide whether your objects can be compared, printed, or found again, and getting one of them wrong makes data disappear.The Object classequals()hashCode()The equals and hashCode contracttoString()Core24 min5 exercises
  4. 8.4EnumsA type with a fixed set of named values, where the compiler refuses to let you invent a new one. It is the only place in Java where the compiler will tell you that you forgot a case.enumCore18 min4 exercises
  5. 8.5Interfaces Deep DiveDefault methods, static methods, marker interfaces, and the one that changes everything: an interface with exactly one method left to implement.Default methodFunctional interfaceMarker interfaceCore20 min4 exercises