Object Oriented

Modeling the
Real World

Object-Oriented Programming (OOP) is a paradigm that organizes software design around data (attributes) and logic (methods), rather than just logic.

Why use OOP?
  • Modularity: Code is easier to troubleshoot and maintain.
  • Reuse: Don't repeat yourself (DRY) via inheritance and composition.
  • Scalability: Easier to manage large systems by breaking them into object interactions.
01.a / The Blueprint

Classes & Objects

Think of a Class as an architectural blueprint. It describes what a house looks like but you can't live in it. An Object is the actual house built from that blueprint. This process is called Instantiation.

Stack vs Heap Memory
When you write Car myCar = new Car();:
  • Stack: Holds the reference variable myCar (fast, strictly ordered execution memory).
  • Heap: Holds the actual object instance (large, free-floating storage memory).
Class Definition
class Car {
  constructor(color) {
    this.color = color;
    this.id = rand();
  }
  // Destructor (conceptual)
  ~Car() { cleanup(); }

}
This code defines structure but takes up no memory until called.
Memory Heap
No instances created yet.
Status
Waiting for instantiation...

Class vs Object vs Structure

Entity Nature Memory Analogy
Class Blueprint / Template None (Logical definition) The Architect's Drawing
Object Instance / Entity Heap Allocation The Actual House
Structure Lightweight Data Container Stack (Value Type) A Post-it Note

* Note: In C++, structs default to public access, classes to private. In C#, structs are value types (stack), classes are reference types (heap).

01.b / Lifecycle

Constructors & Destructors

A Constructor breathes life into an object (Initialization). A Destructor takes it away (Clean-up). This cycle ensures resources (like file handles or network connections) are managed properly.

The 'this' Keyword Inside a constructor, this refers to the specific instance currently being created. It prevents ambiguity between class attributes and parameters.
Default
Robot() {
  this.name = "Droid";
}

Initializes object with hardcoded default values. No arguments required.

Parameterized
Robot(name) {
  this.name = name;
}

Initializes object with specific values passed as arguments during creation.

Copy
Robot(other) {
  this.name = other.name;
}

Creates a new object by copying the state of an existing object.

Object Instances
No robots built yet.
Param:
02 / Protection

Encapsulation

Encapsulation bundles data (variables) and methods (functions) together and restricts direct access to some of an object's components. This is the "Black Box" principle: you know what the object does, but not necessarily how it stores its data internally.

Access Modifiers
  • Public: Accessible by everyone.
  • Private: Accessible only within the class itself.
  • Protected: Accessible by the class and its subclasses (Inheritance).
$1000
LOCKED
Bad Practice obj.balance = 2000;

Direct access bypassing security.

Good Practice obj.deposit(100);

Use a public method to validate.

Security Audit Log
> System initialized.
03 / Reusability

Inheritance

Inheritance allows a class (Child) to derive methods and properties from another class (Parent). It establishes an "Is-A" relationship (e.g., A Car is a Vehicle). This creates a hierarchy and reduces code duplication.

The 'super' Keyword Used inside a child class to call the parent's constructor or methods. For example, super() initializes the parent part of the object before the child adds its own specific properties.

Single

A
B

Multilevel

A
B
C

Hierarchical

A
B
C

Multiple

A
B
C
The Diamond Problem

If A and B both have run(), which one does C inherit? Ambiguity!

Parent (SuperClass)
Vehicle
Properties
speed
engine
Child (SubClass)
Car
↳ speed
↳ engine
+ trunk
Child (SubClass)
Bike
↳ speed
↳ engine
+ kickstand

Notice how adding to Parent automatically updates both Children.

04.a / Method Overriding

Runtime Polymorphism

Method Overriding allows a child class to provide a specific implementation of a method that is already provided by its parent. The method name `speak()` is the same, but the result differs based on the object type at runtime. This implies the object can take many forms (Poly-morphism).

Late Binding This is also known as Dynamic Binding. The decision of exactly which method to run is deferred until the program is actually running (runtime), rather than when it's compiled.
const animals = [ new Dog(), new Cat(), new Duck() ];

// We call the SAME method on all of them:
animals.forEach(animal => {
  animal.speak(); // The execution morphs based on type
});
🐕
Dog Class
Click Me
🐈
Cat Class
Click Me
🦆
Duck Class
Click Me
04.b / Method Overloading

Compile-Time Polymorphism

Method Overloading happens when multiple methods share the same name but have different parameters (signatures). Think of a "Smart Printer" that knows how to handle text, numbers, or images differently, even though the command is always `print()`.

Early Binding Also known as Static Binding. The compiler knows exactly which method to call before the program runs, simply by looking at the types of arguments you pass.
Smart Processor
Ready...
void process(int n) { return n * n; }
void process(String s) { return s.toUpperCase(); }
04.c / Contracts

Interfaces

An Interface is a strict contract. It defines what a class must do, but not how. Unrelated classes (like a Bird and an Airplane) can implement the same `IFlyable` interface, ensuring they both have a `fly()` method.

Interface Types
  • Normal: Contains methods declarations.
  • Marker: Empty interface, used to tag classes (e.g., Serializable).
  • Functional: Contains exactly one abstract method (SAM), used in Lambda expressions.
interface IFlyable {
  void fly();
}
Implements Contract
🚁
Drone
Idle
🦅
Bird
Idle
✈️
Plane
Idle
05 / Simplicity

Abstraction

Abstraction means hiding complex implementation details and showing only the necessary features of an object. It reduces complexity and allows the user to interact with a system without knowing how it works internally.

Abstract Class vs Interface
  • Abstract Class: Cannot be instantiated directly. Use for "is-a" relationships. Can have state (variables) and some implemented methods.
  • Interface: Pure contract, no state. Use for "can-do" capabilities.
void injectFuel(amount) {
  if (temp > 90) return;
  valves.open();
}

int calcTorque(rpm) {
  return rpm * 5252;
}
0101010010101010
ERROR_CHECK_SENSORS()
matrix.transform3d()
overflow_buffer_check
...
Simple Interface (Dashboard)
0 MPH
06 / Immutability

The "Final" Trinity

Three keywords that look similar but have very different purposes.

final

The Restrictor.

  • Variable: Cannot change value (Constant).
  • Method: Cannot be overridden overriding.
  • Class: Cannot be inherited.
finally

The Cleaner.

A block used in Exception Handling (`try-catch`). It ALWAYS executes, regardless of whether an exception occurred or not. Used for closing files/db connections.
finalize()

The Undertaker.

A method called by the Garbage Collector before an object is destroyed. *Note: It is deprecated in modern Java (9+) due to unreliability.
07 / Concurrency

Multi-Threading

A Thread is a unit of execution. The Main Thread handles the UI. If you do heavy work on the Main Thread, the app freezes. Multi-threading moves heavy work to a Background Thread, keeping the UI responsive.

Main UI Thread
UI Status
✅ RESPONSIVE
Single Threaded BAD

Runs a heavy loop on the Main Thread. Observe the gear stop spinning.

Multi-Threaded GOOD

Runs task in background (simulated). The gear keeps spinning.

Worker Terminal Idle
08 / Shared Memory

Static Members

Static members belong to the Class itself, not any individual object. They represent shared memory, like a wall clock in a classroom (shared by all students) vs a wristwatch (owned by one).

Memory Efficiency Static variables are initialized only once in memory at the start of execution. They are useful for counters, constants, or utility functions that don't need object state. Note: Static methods cannot access this.
Class Memory (Static)
Robot.count
0
Instance Memory (Heap)
09 / Relationships

Association vs Composition

Not all relationships are equal. Composition (Part-of) means if the parent dies, the child dies (House + Room). Aggregation/Association (Has-a) means the child survives (Library + Book).

UML Representation
  • Composition: Solid/Filled Diamond (♦). Strong lifecycle dependency (The "Part-of" relationship).
  • Aggregation: Hollow/Empty Diamond (♢). Weak lifecycle dependency (The "Has-a" relationship).
Composition (Strong)
House
Room

Result: Room is destroyed with House.

Aggregation (Weak)
Library
Book

Result: Book survives independently.

10 / Memory Management

Garbage Collection

In languages like Java or C#, you create objects but don't delete them manually. The Garbage Collector (GC) runs in the background to reclaim memory from objects that are no longer reachable (have no active references).

Reachability The GC starts from "GC Roots" (like global variables or currently active stack frames) and traces all reachable references. Anything not connected to the root is considered "garbage" and is eligible for deletion.
Heap Memory System: Idle
Heap is empty. Add objects to start.

Click any object to Cut Reference. The GC will automatically sweep it away.

Glossary

Key Definitions

Class

A blueprint or template for creating objects.

Object

An instance of a class containing data and behavior.

Encapsulation

Bundling data and methods that operate on that data within a single unit, restricting direct access.

Inheritance

A mechanism where a new class derives properties and behavior from an existing class.

Polymorphism

The ability of different classes to be treated as instances of the same general class through a common interface.

Abstraction

Hiding complex implementation details and showing only the necessary features of an object.

Constructor

A special method called when an object is instantiated to initialize it.

Interface

A contract that defines a set of methods that a class must implement.

Static

A keyword indicating that a member belongs to the class itself rather than to any specific instance.

Garbage Collection

Automatic memory management that reclaims memory occupied by objects that are no longer in use.

08 / Knowledge Check