OOP Notes
Learn how objects are created in memory — the new keyword, memory allocation, reference variables, and object lifecycle in Java, C++, and Python.
public class Main { public static void main(String[] args) { // Creating objects with 'new' Book book1 = new Book("Clean Code", "Robert Martin", 464); Book book2 = new Book("Design Patterns", "GoF", 395);
// Reference copy — both point to the SAME object! Book book3 = book1; book3.markAsRead();
System.out.println(book1); // Clean Code by Robert Martin (464 pages) ✓ // book1 shows as read because book3 IS book1 (same reference) } }
STACK HEAP ┌──────────────┐ ┌─────────────────────────┐ │ book1: 0x100 │────────────>│ title: "Clean Code" │ │ book2: 0x200 │──────┐ │ author: "Robert Martin" │ │ book3: 0x100 │──┐ │ │ pages: 464 │ └──────────────┘ │ │ │ isRead: true │ │ │ └─────────────────────────┘ │ │ │ └────>┌─────────────────────────┐ │ │ title: "Design Patterns" │ │ │ author: "GoF" │ │ │ pages: 395 │ │ │ isRead: false │ │ └─────────────────────────┘ │ └────────>(points to same object as book1)
#include <iostream> #include <string>
class Timer { private: std::string label; double seconds; public: Timer(const std::string& label) : label(label), seconds(0) { std::cout << "Timer '" << label << "' created" << std::endl; }
void tick(double dt) { seconds += dt; } double getTime() const { return seconds; }
~Timer() { std::cout << "Timer '" << label << "' destroyed (was at " << seconds << "s)" << std::endl; } };
int main() { // Stack allocation — automatic lifetime Timer stackTimer("Stack"); // Created here stackTimer.tick(1.5); // Automatically destroyed when function ends
// Heap allocation — manual lifetime Timer* heapTimer = new Timer("Heap"); // Created with 'new' heapTimer->tick(2.0); // Must manually destroy: delete heapTimer; // Without this = MEMORY LEAK
return 0; } // stackTimer destructor called here automatically
| **When to use each | ** |
| - **Stack** | Short-lived objects, known size, automatic cleanup |
| - **Heap** | Long-lived objects, dynamic size, shared ownership |
class GameCharacter: def __init__(self, name, character_class, level=1): self.name = name self.character_class = character_class self.level = level self.health = level * 100 self.inventory = [] print(f"{name} the {character_class} enters the world!")
def level_up(self): self.level += 1 self.health = self.level * 100 print(f"{self.name} reached level {self.level}!")
def pick_up(self, item): self.inventory.append(item) print(f"{self.name} picked up {item}")
warrior = GameCharacter("Thor", "Warrior") mage = GameCharacter("Merlin", "Mage", level=5)
warrior.pick_up("Iron Sword") warrior.level_up()
Objects are garbage collected when no references remain
warrior = None # Object eligible for garbage collection
public class Color { private int red, green, blue;
// Private constructor — forces use of factory methods private Color(int r, int g, int b) { this.red = r; this.green = g; this.blue = b; }
// Factory methods — named constructors public static Color fromRGB(int r, int g, int b) { return new Color(r, g, b); }
public static Color fromHex(String hex) { int r = Integer.parseInt(hex.substring(1, 3), 16); int g = Integer.parseInt(hex.substring(3, 5), 16); int b = Integer.parseInt(hex.substring(5, 7), 16); return new Color(r, g, b); }
public static Color red() { return new Color(255, 0, 0); } public static Color green() { return new Color(0, 255, 0); } public static Color blue() { return new Color(0, 0, 255); } }
// Clear, readable object creation Color sunset = Color.fromRGB(255, 128, 0); Color ocean = Color.fromHex("#006994"); Color primary = Color.red();
Book myBook = null; // No object created! myBook.markAsRead(); // NullPointerException! 💥
// Always check before using if (myBook != null) { myBook.markAsRead(); // Safe }
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Object Creation and Instantiation.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Object Oriented Programming (OOP) topic.
Search Terms
object-oriented-programming, object oriented programming (oop), object, oriented, programming, oop, basics, creation
Related Object Oriented Programming (OOP) Topics