Learning guides →

· Albion Gateway College

Java OOP tutorial: design a stock class with a clear invariant

Practise fields, constructors, object state and encapsulation with an original stock-item exercise and boundary checks.

Give the object one responsibility

Define StockItem as storing one item name and quantity while maintaining a non-negative stock count. Decide its responsibility before adding fields or methods. Keep unrelated file reading and printing out of the initial design.

The official Java learning site introduces classes, fields, constructors and objects. This is an independent practice design rather than a model answer for a particular assessment.

Worked design: protect an invariant

Use instance fields name and quantity, with a constructor that receives the initial values. Explicitly reject an initial quantity of -1 while accepting 0. Record quantity >= 0 as the invariant.

Make quantity private and expose purposeful operations such as addStock(int amount) and removeStock(int amount). This limits how callers can change the state.

Validate before changing state

For removeStock, first reject negative amounts, then reject requests larger than available stock. Change quantity only after both checks pass. Mutating first creates an unnecessary recovery problem.

Starting at 3, removing 2 should give 1. Removing 4 should fail while leaving the state at 3. Decide and document what removing zero means.

Self-check: independent instances

Create A with 3 units and B with 8. Remove 1 from A only: A should contain 2 and B should still contain 8. A shared static quantity would not represent independent item stock correctly.

Bring your responsibility statement, field list, boundary cases and own attempt to a tutorial. Students remain responsible for producing their assessed code within university rules.

References

Your next step

For a module-support enquiry, describe the module, learning goal and what you have tried. Appropriate teaching availability requires confirmation; assessed work remains your own.

Continue reading

College online consultation

Welcome

Hello and welcome! Are you a student, an admissions partner, a job seeker, or applying to become a tutor? Please tell us what you would like help with.

[email protected]