Week 10: Object-Oriented Programming (OOP)

4402 words
22 min read
2026-09-12T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

Classes as blueprints, objects as instances, encapsulation, abstraction, private attributes, and state methods. # Computational Thinking — Week 10: Object-Oriented Programming (OOP) One correction first: the official syllabus says **Week 9 is Backtracking, Tree, DFS, and Recursion**; my previous note incorrectly int...

Computational Thinking — Week 10: Object-Oriented Programming (OOP)

One correction first: the official syllabus says Week 9 is Backtracking, Tree, DFS, and Recursion; my previous note incorrectly introduced BFS as a Week 9 topic. The graph-traversal material is still useful, but BFS is not listed in the Week 9 syllabus.
Week 10 officially covers Object-Oriented Programming, Class, Object, Encapsulation, Abstraction, Information Hiding, and Access Specifiers.

TL;DR

Object-oriented programming changes the way we organize a program.
Earlier we often thought in terms of:
text
data
+
procedures that operate on data
OOP groups related data and operations together:
text
        OBJECT
      /        \
   state      behavior
   data       methods
The core vocabulary:
ConceptMeaning
ClassBlueprint/type describing objects
ObjectIndividual instance of a class
Attribute / fieldData stored inside an object
MethodOperation associated with an object/class
EncapsulationBundle state and operations together
AbstractionExpose what matters; hide unnecessary details
Information hidingRestrict direct access to implementation details
Access specifierRule controlling who may access a member
A useful mental model:
Class→Objects→State + Behaviour\boxed{ \text{Class} \rightarrow \text{Objects} \rightarrow \text{State + Behaviour} }

1. Why OOP appears at all

Suppose we want to represent bank accounts.
A procedural-style representation might maintain separate data:
text
account_number
owner
balance
and separate procedures:
text
deposit(...)
withdraw(...)
getBalance(...)
But the data and operations logically belong together.
OOP packages them into one conceptual unit:
text
BankAccount
├── accountNumber
├── owner
├── balance
├── deposit()
├── withdraw()
└── getBalance()
That unit is described by a class.

2. Object-oriented programming

Object-Oriented Programming, or OOP, organizes computation around objects.
An object usually has:
  1. identity
  2. state
  3. behaviour
For example, a student object might have:
text
identity:
    Student #123

state:
    name
    marks
    attendance

behaviour:
    updateMarks()
    calculateGrade()

3. Object identity

Two objects can contain identical data while still being distinct objects.
Imagine:
text
Student A:
    name = "Ravi"
    marks = 80

Student B:
    name = "Ravi"
    marks = 80
Their current state may match, but conceptually they are still two different student objects.
So:
same state⇏same object\boxed{ \text{same state}\not\Rightarrow\text{same object} }

4. State

The state of an object is represented by the values stored in its attributes/fields.
Suppose:
text
Account:
    balance = 5000
After:
text
deposit(1000)
state becomes:
text
balance = 6000
The object persists while its state changes.

5. Behaviour

Behaviour describes what an object can do.
For an account:
text
deposit(amount)
withdraw(amount)
getBalance()
For a car:
text
start()
accelerate()
brake()
For a list:
text
insert()
remove()
sort()
These operations are commonly represented by methods.

6. Class

A class specifies the structure and behaviour shared by a category of objects.
Think:
Class = blueprint / specification\boxed{ \text{Class = blueprint / specification} }
Example:
text
class Student
    name
    marks

    procedure updateMarks(...)
    procedure getGrade(...)
This does not necessarily describe one particular student.
It describes what a Student object looks like.

7. Object

An object is a concrete instance of a class.
If:
text
Student
is a class, then:
text
s1
s2
s3
can be separate Student objects.
Conceptually:
text
s1:
    name = A
    marks = 75

s2:
    name = B
    marks = 90

8. Class vs object

The distinction is fundamental:

Class

text
Student
defines the general pattern.

Object

text
Student(name="A", marks=75)
is one specific instance.
Another analogy:
class:object≈blueprint:building\text{class}:\text{object} \approx \text{blueprint}:\text{building}
The analogy is imperfect, but useful initially.

9. Many objects from one class

A single class can generate many objects.
text
Class: Circle
Objects:
text
c1: radius = 2
c2: radius = 5
c3: radius = 10
They share the same conceptual structure and methods while maintaining different states.

10. Attributes / fields

An attribute stores information associated with an object.
For:
text
class Rectangle
attributes might be:
text
length
width
Object:
text
r1.length = 5
r1.width  = 3
Its state is:
(5,3).(5,3).

11. Methods

A method is an operation associated with a class/object.
For Rectangle:
text
area()
perimeter()
Conceptually:
area=length×width.area=length\times width.
So:
text
r1.area()
might return:
5×3=15.5\times3=15.

12. Methods can inspect object state

Example:
text
procedure area():
    return length * width
The method uses fields belonging to the object.
For:
text
r1 = (length=5,width=3)
it returns:
15.15.
For another object:
text
r2 = (length=10,width=2)
the same method definition returns:
20.20.
Same behaviour, different state.

13. Methods can modify object state

Suppose:
text
class Counter
    value

    procedure increment():
        value = value + 1
Start:
text
c.value = 0
After:
text
c.increment()
state:
text
c.value = 1
After another call:
text
c.value = 2

14. Constructor intuition

When an object is created, it often needs an initial valid state.
Conceptually:
text
create Account(owner, initialBalance)
might initialize:
text
owner = supplied owner
balance = supplied initial balance
A special initialization operation is commonly called a constructor.
The Week 10 syllabus does not explicitly list constructors, but they are a natural supporting concept for understanding class/object creation.

15. Example object creation

Class:
text
class Point
    x
    y
Create:
text
p1 = Point(2, 5)
p2 = Point(7, 1)
Then:
text
p1.x = 2
p1.y = 5

p2.x = 7
p2.y = 1
Both belong to the same class but have independent states.

16. Why classes are useful

Classes help organize related information and operations.
Without grouping:
text
studentName1
studentMarks1
studentAttendance1

studentName2
studentMarks2
studentAttendance2
becomes awkward.
With objects:
text
student1
student2
each object contains its own related state.

17. Encapsulation

Encapsulation is one of the main Week 10 concepts.
At an introductory level:
Encapsulation bundles data together with the operations that manipulate that data.
So instead of:
text
balance
floating separately from:
text
deposit()
withdraw()
we conceptually put them inside:
text
BankAccount

18. Encapsulation example

text
BankAccount
├── balance
├── deposit(amount)
├── withdraw(amount)
└── getBalance()
The balance belongs to the account, and the methods define meaningful operations over that balance.

19. Why encapsulation helps

It creates a clear boundary:
text
outside world
       |
       v
+----------------+
| BankAccount    |
|----------------|
| internal state |
| methods        |
+----------------+
Users of the object interact through defined operations rather than manipulating unrelated variables everywhere.

20. Encapsulation is not merely "make everything private"

A common oversimplification is:
encapsulation = private variables.
That is incomplete.
The larger idea is:
state + related behaviour bundled into a coherent unit\boxed{ \text{state + related behaviour bundled into a coherent unit} }
Access restriction can support encapsulation, but it is not the whole concept.

21. Abstraction

Abstraction means presenting the essential behaviour of something while suppressing unnecessary implementation details.
Example:
When using:
text
car.brake()
you care that the car slows down.
You usually do not need to know the precise hydraulic, electronic, or mechanical implementation.
So:
Abstraction asks: What can this object do?\boxed{ \text{Abstraction asks: What can this object do?} }
rather than forcing every user to know:
How exactly does it do it internally?

22. Interface vs implementation

This gives two conceptual layers.

Interface

What the object exposes:
text
deposit(amount)
withdraw(amount)
getBalance()

Implementation

How those operations are carried out internally.
A user can often work with the interface without understanding every internal detail.

23. Example of abstraction

Suppose a Stack object supports:
text
push(x)
pop()
isEmpty()
A user only needs the abstract stack behaviour:
LIFO.\text{LIFO}.
Internally, it might use:
  • a list
  • an array
  • linked nodes
The user need not know.
That separation is abstraction.

24. Abstraction reduces cognitive load

Without abstraction:
text
To use system X:
understand 147 internal implementation details
With abstraction:
text
Call operation A
Call operation B
Observe result C
The internal complexity remains, but users interact with a simpler model.

25. Information hiding

Information hiding means deliberately keeping implementation details inaccessible or invisible when external code should not depend on them.
Example:
text
BankAccount
might hide:
text
balance
from direct modification.
Instead users must call:
text
deposit()
withdraw()

26. Why hide information?

Suppose external code can directly do:
text
account.balance = -1000000
That may violate the rules of the object.
If balance changes only through:
text
withdraw(amount)
the method can enforce conditions such as:
text
if amount <= balance:
    allow withdrawal
Information hiding helps preserve valid state.

27. Invariant

An invariant is a condition intended to remain true for valid objects.
Example:
balance≥0balance\geq0
if overdrafts are forbidden.
Methods can enforce this invariant.
If arbitrary outside code can directly change balance, the invariant becomes harder to guarantee.

28. Example

Suppose:
text
Account
    hidden balance

    deposit(x):
        if x > 0:
            balance = balance + x

    withdraw(x):
        if x > 0 AND x <= balance:
            balance = balance - x
Now the class itself controls how its state changes.

29. Encapsulation vs information hiding

These ideas are related but distinct.

Encapsulation

Bundle:
data + operations\text{data + operations}
inside one unit.

Information hiding

Prevent external code from depending directly on internal representation/details.
A class can encapsulate fields and methods while also hiding some of them.

30. Abstraction vs information hiding

Also related, but not identical.

Abstraction

Focus attention on essential external behaviour.
What does this thing do?

Information hiding

Conceal implementation details that users should not access or rely on.
What details should outsiders not see/use directly?
A well-designed object often uses both.

31. Example tying all three together

Consider:
text
class TemperatureSensor
Internally it may store:
text
rawVoltage
calibrationConstant
Publicly it exposes:
text
getTemperature()

Encapsulation

Sensor state and sensor operations are grouped together.

Abstraction

Caller simply asks for temperature.

Information hiding

Caller does not directly manipulate rawVoltage or calibration internals.

32. Access specifier

An access specifier controls which parts of a program may access a class member.
Common conceptual categories include:
  • public
  • private
  • protected
The exact syntax and semantics depend on the programming language.
Week 10 explicitly includes Access specifiers.

33. Public

A public member is intended to be accessible from outside the class.
Example:
text
public:
    deposit()
    withdraw()
External code may call:
text
account.deposit(500)
Public members commonly form the object's interface.

34. Private

A private member is intended to be accessible only within the class or according to the language's private-access rules.
Example:
text
private:
    balance
Outside code should not directly do:
text
account.balance = ...
Instead:
text
account.getBalance()
may expose an appropriate view.

35. Protected

A protected member usually has access rules between public and private, commonly allowing the class and certain derived/subclass contexts to access it.
The exact meaning varies by programming language.
For Week 10, remember the broad hierarchy:
text
public    → broadly accessible
protected → restricted, often class/subclass related
private   → strongly restricted to implementation

36. Why access specifiers matter

They help define:
what is part of the public contract\boxed{ \text{what is part of the public contract} }
versus:
what is internal implementation\boxed{ \text{what is internal implementation} }
This reduces accidental misuse.

37. Example design

Instead of:
text
class Account
    public balance
a better design may be:
text
class Account
    private balance

    public deposit(amount)
    public withdraw(amount)
    public getBalance()
Then state changes pass through controlled operations.

38. Getters

A getter provides controlled read access.
Example:
text
procedure getBalance():
    return balance
The internal field remains hidden, while callers can retrieve its value.

39. Setters

A setter provides controlled write access.
Example:
text
procedure setAge(x):
    if x >= 0:
        age = x
Unlike direct assignment:
text
age = -50
the setter can validate incoming values.

40. Getter/setter warning

Using getters and setters for every field does not automatically create good abstraction.
For example:
text
getBalance()
setBalance(anything)
may expose nearly the same unrestricted state as a public field.
The design question is:
What operations should users actually be allowed to perform?

41. Object interface

An object's interface consists conceptually of the operations accessible to its users.
For example:
text
Queue
├── enqueue(x)
├── dequeue()
├── front()
└── isEmpty()
A user need not care how the queue stores elements internally.

42. Implementation can change

Suppose Queue originally uses:
text
list
and later uses:
text
circular array
If the public interface remains:
text
enqueue()
dequeue()
client code may require no changes.
This is one major benefit of abstraction and information hiding.

43. Representation independence

If users rely only on the public interface, internal representation can potentially change without breaking them.
Conceptually:
text
version 1:
Queue internally = List

version 2:
Queue internally = CircularArray
External use:
text
q.enqueue(x)
q.dequeue()
can remain unchanged.

44. Method call as message intuition

A method invocation such as:
text
account.withdraw(500)
can be understood as:
Ask/send a request to the account object to perform withdraw with parameter 500.
This becomes especially relevant because Week 11 explicitly introduces message passing and RPC.

45. Object state is usually object-specific

Suppose:
text
a1.balance = 500
a2.balance = 1000
Calling:
text
a1.deposit(100)
should normally change:
text
a1.balance
to:
600600
while:
text
a2.balance
remains:
1000.1000.
Each object maintains its own state unless some state is explicitly shared.

46. Class-level vs object-level state

A useful supporting distinction:

Instance/object state

Different for each object.
text
student1.marks
student2.marks

Class/shared state

Potentially shared across all instances.
For example:
text
numberOfStudentsCreated
The Week 10 syllabus does not explicitly name static/class fields, so treat this as supporting context rather than a core listed topic.

47. Example: Circle class

Conceptually:
text
class Circle
    private radius

    public setRadius(r):
        if r >= 0:
            radius = r

    public area():
        return π * radius * radius
Create:
text
c1 = Circle()
c1.setRadius(5)
Then:
c1.area()=25π.c1.area()=25\pi.

48. What is encapsulated here?

Inside Circle:
text
radius
setRadius()
area()
all belong to one conceptual entity.
That is encapsulation.

49. What is abstracted?

External code can ask:
text
c1.area()
without needing to reproduce:
πr2\pi r^2
everywhere.
The Circle object provides the higher-level operation.

50. What is hidden?

If:
text
radius
is private, external code cannot freely manipulate its internal representation.
It must use defined operations such as:
text
setRadius()
That is information hiding.

51. Why invalid state matters

Imagine:
text
radius = -5.
That would not make sense for an ordinary circle model.
If radius is hidden and changed only through:
text
setRadius(r)
the class can reject:
r<0.r<0.
Thus object methods enforce semantic rules.

52. Example: Student

text
class Student
    private marks

    public setMarks(x):
        if 0 <= x AND x <= 100:
            marks = x

    public getMarks():
        return marks

    public passed():
        return marks >= 40
This integrates earlier CT concepts:
  • variables
  • selection
  • AND
  • procedures
  • state
  • access control

53. Object-oriented design as modelling

OOP often starts by identifying:

Objects/entities

text
Student
Course
Account
Book

State

text
Student → name, marks
Course  → title, credits

Behaviour

text
Student → updateMarks()
Course  → enroll()
This is a way of translating a domain into computational abstractions.

54. Class relationship to datatype

A class can be understood as defining a new kind of structured datatype.
Earlier:
text
Integer
Boolean
List
were types.
With OOP, one may define:
text
Student
BankAccount
Point
as custom structured types.
Then variables can refer to objects of those types.

55. Object reference intuition

Suppose:
text
a = someObject
b = a
In many OOP languages, a and b may refer to the same underlying object rather than creating two independent copies.
Then a mutation through:
text
a
may be visible through:
text
b.
This depends on the language/object model, but it is an important general object concept.

56. Identity vs equality

Two useful questions:

Equality

Do these objects currently contain equivalent values?

Identity

Are these actually the same object?
Those questions need not have the same answer.
Example:
text
Point(2,3)
Point(2,3)
may be equal in value but still be separate objects.

57. Side effects revisited

Remember Week 3's side effects.
A method such as:
text
account.deposit(100)
has a side effect:
balancenew=balanceold+100.balance_{\text{new}} = balance_{\text{old}}+100.
OOP frequently involves controlled mutation of object state.

58. Procedure vs method

A procedure/function can be standalone.
A method belongs conceptually to a class/object.
Compare:
text
deposit(account, amount)
with:
text
account.deposit(amount)
Both may accomplish related computation, but the latter associates the operation directly with the object.

59. Method parameter and receiver

In:
text
account.deposit(500)
conceptually there are two pieces:
  • object receiving the request:
    text
    account
    
  • explicit argument:
    text
    500
    
The method operates using both the object's current state and supplied arguments.

60. Trace example

Suppose:
text
class Counter
    private value

    increment():
        value = value + 1

    add(x):
        value = value + x
Object starts:
text
c.value = 0
Operations:
text
c.increment()
c.add(4)
c.increment()
State trace:
0→1→5→6.0\to1\to5\to6.
Final:
6\boxed{6}

61. Two-object trace

Create:
text
c1.value = 0
c2.value = 10
Execute:
text
c1.increment()
c1.increment()
c2.increment()
Final:
c1.value=2c1.value=2 c2.value=11.c2.value=11.
Do not accidentally merge state belonging to different objects.

Common mistake: class = object
Wrong.
text
Car
can be the class.
text
myCar
is one object/instance.
One class may correspond to many objects.

Common mistake: object = just data
An object generally combines:
state + behaviour + identity\boxed{ \text{state + behaviour + identity} }
Thinking of it as only a dictionary of fields misses much of the OOP model.

Common mistake: encapsulation = hiding
Not exactly.
Encapsulation:
bundle related state and behaviour.
Information hiding:
restrict exposure of implementation details.
They often work together, but they are not synonyms.

Common mistake: abstraction = simplification only
Abstraction is not merely "make it easier."
It means:
expose the relevant conceptual interface while suppressing lower-level details.
A good abstraction deliberately chooses what the user should think about.

Common mistake: private means secure/encrypted
No.
private is primarily a programming-language access/control concept.
It does not automatically mean:
  • encrypted
  • confidential against attackers
  • inaccessible at machine level
It helps enforce program structure.

Common mistake: public data is always bad
Not necessarily.
The design depends on what invariants and abstraction boundaries matter.
The point is not:
everything must be private.
The point is:
expose only what should legitimately form the external interface.

Common mistake: setters are simple assignment
A setter can contain logic:
text
setAge(x):
    if x >= 0:
        age = x
So controlled access can include:
  • validation
  • transformation
  • rejection
  • logging
  • related state updates

Common mistake: methods share all state globally
Two objects of the same class normally have separate instance state.
If:
text
a1.balance = 100
a2.balance = 900
calling a method on a1 should not automatically alter a2.
Always track which object receives the method call.

Common mistake: abstraction means implementation does not exist
The implementation still exists.
It is simply placed behind an interface so users do not need to reason about it constantly.
Think:
text
visible contract
----------------
hidden machinery
not:
text
visible contract
----------------
nothing underneath

Common mistake: access specifiers are identical across languages
They are not.
Languages differ in:
  • syntax
  • enforcement
  • inheritance rules
  • module/package access
For CT, focus on the conceptual purpose rather than assuming one particular language's exact rules.

72. OOP trace strategy

For pseudocode involving objects, make a state table per object.
Example:
StepObjectOperationState beforeState after
1adeposit(50)balance=100balance=150
2bwithdraw(20)balance=90balance=70
3awithdraw(40)balance=150balance=110
This avoids mixing objects.

73. Identify access before tracing

If pseudocode tries:
text
object.privateField = x
ask whether that operation is permitted under the stated access rules.
The correct response may be:
access is not permitted
rather than mechanically changing the value.

74. Object invariant strategy

When examining a class:
  1. Identify fields.
  2. Identify valid-state conditions.
  3. Identify methods that change state.
  4. Check whether methods preserve those conditions.
  5. Identify what external code is allowed to access.
This captures the logic behind encapsulation and information hiding.

75. Example: bounded counter

Suppose:
text
class Counter
    private value

    increment():
        if value < 10:
            value = value + 1
Invariant:
value≤10.value\leq10.
Start:
value=9.value=9.
First increment:
9→10.9\to10.
Second increment:
condition:
10<1010<10
is false.
So:
value=10\boxed{value=10}
remains.

76. Interface design example

For a bank account, compare:

Poor abstraction

text
setBalance(any number)

Domain-oriented abstraction

text
deposit(amount)
withdraw(amount)
The second interface reflects meaningful operations in the domain and makes invariant enforcement easier.

77. OOP and earlier CT concepts

Week 10 is not disconnected from earlier weeks.
A method can contain:
text
variables
loops
conditions
lists
tables
dictionaries
graphs
recursion
OOP provides another organizational layer around those computations.

78. Procedural vs object-oriented framing

Suppose we need to calculate area of circles.

Procedural

text
area(radius)

OOP

text
circle.area()
Neither style is inherently "always superior."
The distinction is about how data and operations are organized.

79. OOP does not replace algorithms

A class can still contain inefficient algorithms.
For example:
text
Graph.shortestPath()
being a method tells us nothing by itself about whether its algorithm is correct or efficient.
OOP addresses program organization and modelling; algorithms address computational procedures.

80. Compact terminology sheet

Class

definition/blueprint for objects\boxed{ \text{definition/blueprint for objects} }

Object

instance of a class\boxed{ \text{instance of a class} }

Attribute

state/data belonging to an object\boxed{ \text{state/data belonging to an object} }

Method

operation associated with a class/object\boxed{ \text{operation associated with a class/object} }

Encapsulation

bundle state + behaviour\boxed{ \text{bundle state + behaviour} }

Abstraction

expose essentials, suppress unnecessary detail\boxed{ \text{expose essentials, suppress unnecessary detail} }

Information hiding

restrict dependence/access to implementation details\boxed{ \text{restrict dependence/access to implementation details} }

Access specifier

rule controlling visibility/access\boxed{ \text{rule controlling visibility/access} }

81. Public / private / protected summary

AccessBasic intuition
publicAvailable through the external interface
privateInternal implementation detail
protectedRestricted access, commonly involving class/subclass contexts
Exact rules are language-dependent.

82. Concept map

text
OBJECT-ORIENTED PROGRAMMING
│
├── Class
│    └── defines structure + operations
│
├── Object
│    ├── identity
│    ├── state / attributes
│    └── behaviour / methods
│
├── Encapsulation
│    └── state + methods bundled together
│
├── Abstraction
│    └── expose useful interface
│
├── Information Hiding
│    └── conceal implementation details
│
└── Access Specifiers
     ├── public
     ├── protected
     └── private

83. What you should actually master

By the end of CT Week 10, you should be able to:
  1. Explain the basic idea of OOP.
  2. Distinguish a class from an object.
  3. Identify object state and behaviour.
  4. Distinguish an attribute/field from a method.
  5. Trace state changes in multiple objects separately.
  6. Explain encapsulation.
  7. Explain abstraction.
  8. Explain information hiding.
  9. Distinguish those three concepts rather than treating them as synonyms.
  10. Explain why direct unrestricted access to internal fields can be problematic.
  11. Understand object invariants.
  12. Explain the purpose of public/private/protected access.
  13. Recognize an object's public interface.
  14. Understand how methods can validate and control state changes.
  15. Recognize that implementation may change while an abstract interface stays stable.
  16. Connect method calls to earlier ideas of procedures, parameters and side effects.
If these are comfortable, CT Week 10 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 10 Diagnostic: In Object-Oriented Programming, what is the relationship between a Class and an Object? :: Answer: B — A Class defines the attributes and behavior; an Object is a concrete realization created in memory from that blueprint.
  • Week 10 Diagnostic: The principle of bundling data and methods that manipulate that data within a single unit while restricting direct outside access is called: :: Answer: B — Encapsulation hides the internal representation and bundles data with methods.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

In Object-Oriented Programming, what is the relationship between a Class and an Object?
MCQ
3 Unit Assessment
A. A Class is an instance of an Object
B. A Class is a blueprint / template; an Object is a concrete instance of that Class
C. They are completely identical synonyms
D. A Class can only contain functions, not data
2

Question 2

The principle of bundling data and methods that manipulate that data within a single unit while restricting direct outside access is called:
MCQ
3 Unit Assessment
A. Inheritance
B. Encapsulation
C. Polymorphism
D. Recursion

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.