A class defines a type's state and behavior; an object is an instance with its own state. Keep invariants inside methods rather than allowing unrelated code to change fields freely.
Before you begin
Be comfortable with variables, conditions, loops and basic methods. Use a small local project with a recorded JDK version and keep the input data fictional.
Work through the idea
Write the expected behavior before implementing the exercise. Keep the first version small enough to trace manually, then change one input or requirement. Record both the successful path and an invalid or empty-input case so that the result demonstrates reasoning rather than a copied output.
- Define a constructor
- Encapsulate fields
- Separate instance and static responsibilities
Practice task
Create an inventory item with a name and a nonnegative stock quantity.
Check your result
Test two independent objects and reject a stock update that violates the invariant.
A mistake to avoid
Do not put every object's mutable state in static fields.
Keep a review note
Save the inputs or scenario, your reasoning and the result you checked. Explain one assumption and one case that needs more work. Revise the exercise after feedback and distinguish what you demonstrated from what remains untested.
Official reference for further study
Explore the related learning path · Choose another worksheet
