Enums in Java
An enum is a class with a fixed set of instances, which makes an invalid value impossible rather than merely unlikely.
Material for readers past the basics.
145 notes tagged
An enum is a class with a fixed set of instances, which makes an invalid value impossible rather than merely unlikely.
A class declared inside another can be static, inner, local or anonymous, and the difference is mainly what each one can see.
instanceof tests the runtime type, and since Java 16 it can bind a typed variable in the same step.
final means cannot be reassigned, cannot be overridden or cannot be extended, depending on where it is written.
Two objects that are equal must have the same hash code. Breaking that contract quietly breaks every hash based collection.
Every class inherits from Object, which is where toString, equals, hashCode and getClass come from.
From new to unreachable: how objects are created, how long they live, and what actually happens when nothing references them any more.
Most relationships between classes are has-a, not is-a. Composition is usually the more flexible and more honest design.
Abstraction exposes what a type does and hides how. Abstract classes share partial implementation, interfaces declare a capability.
One reference type, many possible behaviours. Polymorphism is what lets code work with a supertype and stay correct as new subtypes appear.
A subclass replaces inherited behaviour by declaring the same signature, and the JVM chooses the version at runtime from the actual object.
Four levels of visibility control who can see a member, and choosing the narrowest one that works is the single easiest design win.