Tutorial 2: Objects and Object-Oriented Programming Languages

Unit 3 ยท Section 2

Objectives

Object-oriented programming organizes software around objects that combine state with operations. Encapsulation protects invariants; abstraction exposes a useful interface. Inheritance can represent substitutability, but composition often avoids fragile hierarchies.

class Account {
    private double balance;
    void deposit(double amount) { if (amount > 0) balance += amount; }
}

Exercises

  1. Design a class for a library loan.
  2. State its invariant and public operations.
  3. Compare inheritance with composition for notifications.

Self-check

  1. What is encapsulation?
  2. What is an invariant?
  3. When is composition preferable?

Self-Check Quiz

1. What does an object combine?

AnswerState and behavior behind an interface.

2. Why hide fields?

AnswerTo protect invariants and allow representation to change without breaking clients.

Homework

  1. Model a small domain with three classes.
  2. Define relationships and invariants.
  3. Justify one composition or inheritance choice.
Sample answerA loan can reference a book and member, expose return behavior, and protect its due-date invariant. Notification behavior can be composed as an independent service rather than inherited into every domain class.