Classes and Instances
- Blueprints and objects. A class is the blueprint; new creates an instance: its own fields, its own identity on the heap.
- Fields. Fields are the state each instance carries: declared with types, initialised in constructors.
- References. Object variables hold references: two variables can point at one object, and == compares the pointers, not the data.
Encapsulation and Constructors
- private fields. Encapsulation makes fields private and exposes behaviour through methods: internals stay changeable.
- Constructors. A constructor runs at new, receiving arguments and establishing the object’s valid starting state.
- Invariants. Constructors and setters defend invariants: an Account that cannot be built with a negative balance.
Composition and Inheritance
- extends. The extends keyword makes a subclass inherit fields and methods: and super reaches the parent’s versions.
- Overriding. Overriding replaces a parent method in the child: marked @Override so typos fail the compile.
- Prefer composition. Composition: objects holding objects: usually beats deep inheritance: flexible, testable, no fragile base class.
Before and after this level
- Before: Level 1: Java Foundations: Types, Variables and Operators, Conditions and Loops, Methods and Basic Programs.
- Next: Level 3: Interfaces & Polymorphism: Interfaces and Abstract Classes, Dynamic Dispatch, Designing Flexible Object Models.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does Java Level 2: Classes & Objects cover?
Classes and Instances, Encapsulation and Constructors, Composition and Inheritance: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 1: Java Foundations, which covers Types, Variables and Operators, Conditions and Loops, Methods and Basic Programs.