Classes, responsibilities and encapsulation
≈ 45 minClasses, responsibilities and encapsulation
Object-oriented design is not a way of scattering nouns into classes. A useful class owns a small, coherent responsibility, protects the rules that keep its state valid, and collaborates through methods with clear names. A class representing a LibraryLoan can know its due date and whether it is overdue; it should not also decide how a screen is drawn or write directly to a database.
Encapsulation means clients ask an object to do something rather than reaching inside and changing fields. If a balance may never be negative, make the field private and expose a method that validates a withdrawal. This gives one place to test and change the rule. Composition means one object contains or uses another; inheritance should be reserved for a genuine substitutable is-a relationship.
Worked reasoning. A library system has Book, Member and Loan. A Loan refers to one Book and one Member, calculates its own overdue status, and exposes returnBook(). The display layer asks the Loan for information rather than changing dueDate directly. This design makes the rule testable and prevents a screen action from leaving a loan in an impossible state.
Exam lens. In an exam answer, name the responsibility, identify what state must stay valid, and justify whether composition or inheritance matches the relationship. A diagram with arrows is not enough unless the responsibilities make sense.
Uses Uvero's optional secure Java practice service. If it is unavailable, your lessons and progress still work.
Which statement is the most defensible principle for Classes, responsibilities and encapsulation?
Enter the key term for Classes, responsibilities and encapsulation. Which principle keeps an object’s valid state behind methods?
A payment class exposes a public balance field. Which redesign best protects the rule that a balance may not become negative?
Name the concise safeguard or principle that completes this lesson’s scenario: A payment class exposes a public balance field. Which redesign best protects the rule that a balance may not become negative?

