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.
- 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.
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.
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).
constructor(color) {
this.color = color;
this.id = rand();
}
// Destructor (conceptual)
~Car() { cleanup(); }
}
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).
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.
this refers to the specific instance currently being created.
It prevents ambiguity between class attributes and parameters.
this.name = "Droid";
}
Initializes object with hardcoded default values. No arguments required.
this.name = name;
}
Initializes object with specific values passed as arguments during creation.
this.name = other.name;
}
Creates a new object by copying the state of an existing object.
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.
- Public: Accessible by everyone.
- Private: Accessible only within the class itself.
- Protected: Accessible by the class and its subclasses (Inheritance).
obj.balance = 2000;
Direct access bypassing security.
obj.deposit(100);
Use a public method to validate.
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.
super() initializes the parent part of the object before the child adds its own
specific properties.
Single
Multilevel
Hierarchical
Multiple
If A and B both have
run(), which one does C inherit? Ambiguity!
Notice how adding to Parent automatically updates both Children.
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).
// We call the SAME method on all of them:
animals.forEach(animal => {
animal.speak(); // The execution morphs based on type
});
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()`.
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.
- 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.
void fly();
}
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: 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.
if (temp > 90) return;
valves.open();
}
int calcTorque(rpm) {
return rpm * 5252;
}
ERROR_CHECK_SENSORS()
matrix.transform3d()
overflow_buffer_check
...
The "Final" Trinity
Three keywords that look similar but have very different purposes.
The Restrictor.
- Variable: Cannot change value (Constant).
- Method: Cannot be overridden overriding.
- Class: Cannot be inherited.
The Cleaner.
The Undertaker.
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.
Runs a heavy loop on the Main Thread. Observe the gear stop spinning.
Runs task in background (simulated). The gear keeps spinning.
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).
this.
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).
- Composition: Solid/Filled Diamond (♦). Strong lifecycle dependency (The "Part-of" relationship).
- Aggregation: Hollow/Empty Diamond (♢). Weak lifecycle dependency (The "Has-a" relationship).
Result: Room is destroyed with House.
Result: Book survives independently.
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).
Click any object to Cut Reference. The GC will automatically sweep it away.
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.