Object orientation and OO development
Core concepts and practice of object orientation: objects, classes, encapsulation, inheritance, polymorphism, interfaces, coupling/cohesion, and how OO development is used in engineering design and exams.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Object orientation is the main organizing idea used in modern software engineering. Engineers use it to model real systems as interacting objects, to design reusable, maintainable code, and to reason about large systems by separating responsibilities. In practical engineering tasks (analysis, design, implementation and maintenance), OO concepts guide how you partition a system, hide implementation details, and support change.
Key ideas
All terms are defined before use.
Object: an entity that has identity, state, and behavior. Identity means two objects can be distinguished even if they have the same state. State = values of attributes (data). Behavior = methods (operations) the object exposes.
Class: a blueprint or type that defines a set of objects sharing the same structure (attributes) and behavior (methods). A class declaration specifies the attributes, the operations, and visibility (access control) of members.
Encapsulation: the principle of bundling data (attributes) and the methods that operate on the data, and restricting direct access to some of the object's components. Encapsulation is enforced by access control (e.g., private, protected, public). It prevents external code from depending on internal representation.
Abstraction: representing the essential features of an object while hiding unnecessary detail. An abstract class or interface provides an abstract view: it names operations without necessarily providing complete implementations.
Inheritance: a mechanism where a new class (the subclass or derived class) reuses and extends the definition of an existing class (the superclass or base class). Inheritance models an "is-a" relationship.
Exact statement (as used in exams): If class S inherits from class T, then S acquires T's attributes and operations (subject to visibility rules) and may add or override operations. Assumption: language supports single or multiple inheritance as specified; override rules and accessibility follow language semantics.
Polymorphism: ability of code to operate on objects of different classes through a common interface. Important forms:
- Subtype polymorphism (inclusion polymorphism): a reference typed as a superclass or interface can refer to objects of any subtype; method calls are resolved at runtime (dynamic dispatch) according to the object's actual class.
- Ad-hoc polymorphism (overloading): same operation name but different parameter types. (Language-dependent.)
- Parametric polymorphism (generics/templates): code written with type parameters works uniformly for any admissible type (e.g., Java generics, C++ templates).
Message passing / Method call: an object requests another object to perform an operation. In OO architectures, objects interact by sending messages (method invocations).
Coupling: a measure of how strongly connected different modules/classes are. Low coupling means changes in one class cause few changes in others.
Cohesion: a measure of how closely related the responsibilities inside a single class are. High cohesion means a class has a single, well-focused purpose.
Liskov Substitution Principle (LSP) — exact exam-style statement: If S is a subtype of T, then objects of type S may be substituted in any program where objects of type T are expected, without altering desirable program properties (correctness, task performed). Assumptions: preconditions may not be strengthened in a subtype; postconditions may not be weakened; invariants of the supertype must be preserved. This is used to reason about safe inheritance.
Law of Demeter (LoD) — exact exam-style statement: A method M of object O should only call methods of: O itself, M's parameters, any objects created/instantiated within M, O's direct component objects (fields), and global objects. In other words: "only talk to your immediate friends." Assumption: applies to method-level coupling control.
UML class box to draw (describe exactly): Draw a rectangle with three horizontal compartments. Top compartment: class name (write class name centered; if abstract, italicize the name; note: in UML underlining denotes static features, not abstract). For interfaces, annotate the classifier name with <<interface>>. Middle compartment: attributes listed one per line as
visibility name: Type. Bottom compartment: operations listed one per line asvisibility name(params): ReturnType.Associations and multiplicities to draw: For an association between classes A and B, draw a solid line connecting their class boxes. At each end show multiplicity (0..1, 1, 0.., 1..). Label role names near the ends if needed. Use composition (filled diamond at the whole) or aggregation (hollow diamond) to indicate whole–part relationships when appropriate. For inheritance draw a solid line with a hollow triangle arrowhead pointing to the superclass.
Formulas
Programming syntax and short patterns to remember (each on its own line):
class ClassName { /* attributes and methods */ } — class definition; language-dependent syntax (Java/C++/C# use similar names).
class Sub extends Super { /* adds or overrides */ } — Java inheritance syntax; Sub inherits from Super.
interface I { void m(); } — Java-like interface: declares methods without implementation (unless default).
public, protected, private — access modifiers. public (visible to all), protected (visible to subclasses and same package in Java), private (visible only inside the class).
@Override public void m() { ... } — Java annotation indicating method override (helps compiler checks).
class C { private Type a; public Type getA() { return a; } public void setA(Type v) { a = v; } } — standard encapsulation with accessor methods (get/set).
virtual ReturnType m(...) (C++) and virtual ReturnType m(...) = 0; for pure virtual (interface-like) — C++ polymorphism syntax.
Note: exact keywords and rules differ by language (Java vs C++ vs Python); verify language-specific details before quoting in code answers.
Worked examples
Example 1 — design + dynamic dispatch trace (typical long question answer)
Problem: Design classes for bank accounts where SavingsAccount and CheckingAccount inherit from Account. SavingsAccount has interest code, CheckingAccount charges fee. Show a Java-like class sketch and trace a call.
Answer (model):
Classes (UML description to draw):
- Account
- -accountNumber: String
- -balance: double
- +deposit(amount: double): void
- +withdraw(amount: double): boolean
- SavingsAccount (inherits Account)
- -interestRate: double
- +applyInterest(): void
- +withdraw(amount: double): boolean // may override with limits
- CheckingAccount (inherits Account)
- -overdraftLimit: double
- +withdraw(amount: double): boolean // override to allow overdraft with fee Draw inheritance arrows from SavingsAccount and CheckingAccount to Account.
- Account
Java-like code sketch (short):
class Account { private double balance; public boolean withdraw(double a) { if (a<=balance) { balance-=a; return true; } return false; } }class SavingsAccount extends Account { private double interestRate; public boolean withdraw(double a) { /* disallow overdraft */ return super.withdraw(a); } }Dynamic dispatch trace (step-by-step):
- Code:
Account a = new SavingsAccount(); boolean ok = a.withdraw(100.0); - Step 1:
new SavingsAccount()creates an object whose actual class is SavingsAccount; object has identity and state. - Step 2: Reference
ais of static type Account but points to SavingsAccount object. - Step 3: At runtime, the call
a.withdraw(100.0)uses dynamic dispatch: the runtime looks up the withdraw() implementation in the actual class (SavingsAccount). If SavingsAccount overrides withdraw, that implementation runs; otherwise Account.withdraw runs.
- Code:
Final remark: This preserves LSP only if SavingsAccount withdraw obeys Account's contract (no strengthened preconditions).
Example 2 — short modelling question (exam model answer)
Question: Draw a class diagram for a simple Library system (Books, Members, Loans). Explain multiplicities.
Answer (model):
- Classes: Book, Member, Loan.
- Associations: Member — Loan: 0..* at the Loan end (a Member can have zero or many Loans), and 1 at the Member end (each Loan is for exactly one Member). A common correct choice: Member 0..* -borrows-> Loan (each Member can have zero or many Loans), Loan 1 -for-> Book (each Loan is for exactly one Book), Book 0..* -loans-> Loan (a Book can have zero or many Loan records over time). Draw class boxes and association lines with these multiplicities. Include role names near the ends (e.g., borrower at the Member end, book at the Book end). Model attributes like loanDate on the Loan class (not as role names).
- Mention design choices: use composition if a Loan cannot exist without a Member (fill in reasons). Discuss whether to model BookCopy vs Book (for multiple copies).
Common mistakes
- Violating LSP: making a subtype strengthen preconditions or weaken postconditions (e.g., a subclass method that throws new exceptions clients cannot handle).
- Using public attributes instead of accessors: breaks encapsulation and makes future changes harder.
- Forgetting dynamic dispatch rules in trace questions: method called is determined by runtime type, not reference type (for virtual methods).
- Wrong UML multiplicity notation: write
*or0..*consistently; never mixn..mformats incorrectly. - Mixing interface and implementation terms: define interfaces (abstract behaviour) separately from concrete classes that implement them.
For your exam
Kinds of questions you will see:
- Definitions (write precise definitions and short examples): e.g., define class, object, encapsulation, polymorphism.
- Short notes: explain LSP, Law of Demeter, compare inheritance vs composition.
- Derivations/Proof-style: show why LSP implies constraints on pre/postconditions — give the substitution argument.
- Diagram questions: draw UML class diagrams, show attributes, operations, multiplicities, and inheritance arrows.
- Design questions: given a scenario, produce a class model, list responsibilities, and justify choices (coupling/cohesion, reuse, change points).
- Tracing and code: given code, show runtime method resolution and state changes; or write a small class sketch implementing required behaviour.
What a full-marks answer includes:
- Precise definitions (bold or clearly stated) and a simple example.
- Correct diagrams with labeled compartments, attributes and operations, correct multiplicities and arrowheads.
- For design questions: a brief justification mentioning encapsulation, cohesion, low coupling, and LSP adherence.
- For trace/program questions: step-by-step runtime explanation, showing which object's method runs and why.
Quick check
- Define encapsulation in one line.
- In Java, if
A a = new B();and B extends A and overridesm(), whichm()runs ata.m()? (static type vs runtime type?) - State one rule of the Liskov Substitution Principle.
Answers: 1) Encapsulation = bundling data and methods and restricting direct access to data via access control (e.g., private fields and public accessors). 2) The m() of the runtime object's class B runs (dynamic dispatch to B). 3) A subtype must not strengthen the preconditions of its supertype (clients that work with the supertype must work with the subtype).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?