OOP/Lesson 1 of 5/6 min read
Classes and Objects
Classes, objects, constructors, access modifiers, static members, this, object lifecycle and memory, and equality vs identity.
On this page
Object-Oriented Programming
Object-oriented programming (OOP) organizes software around objects that bundle state (fields) and behavior (methods), instead of around functions acting on separate data.
| Procedural | Object-oriented | |
|---|---|---|
| Unit of design | Functions | Objects |
| Data | Passed around, often global | Owned by objects |
| Reuse | Function libraries | Inheritance, composition |
| Example languages | C, Pascal | Java, C++, Python, C# |
Why OOP: models real-world entities, controls complexity through encapsulation, enables reuse and extension, and makes large codebases easier to split among teams.
Class
A class is a blueprint that defines fields and methods. It takes no memory for instance data until objects are created.
public class BankAccount {
private String owner;
private double balance;
public BankAccount(String owner, double initial) {
this.owner = owner;
this.balance = initial;
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amount;
}
public double getBalance() { return balance; }
}Object
An object is an instance of a class with its own state. Every object has:
- State: values of its fields.
- Behavior: the methods it supports.
- Identity: what makes it distinct from other objects with the same state (its memory address).
BankAccount a = new BankAccount("Asha", 100);
BankAccount b = new BankAccount("Ravi", 50);
a.deposit(20); // only a changesMemory: stack vs heap
In Java and C#, the reference variable a lives on the stack (inside the method's frame), while the object itself lives on the heap. When no references remain, the garbage collector reclaims it. In C++, objects can live on either; new puts them on the heap and you must delete them (or use smart pointers).
Constructor
A special method that initializes a new object. Same name as the class (Java, C++), or __init__ in Python. No return type.
| Type | Meaning |
|---|---|
| Default | No arguments; compiler supplies one if you write none |
| Parameterized | Takes arguments to set initial state |
| Copy constructor (C++) | Builds a new object from an existing one |
| Private constructor | Prevents outside instantiation (Singleton, factory methods) |
Constructor chaining: this(...) calls another constructor in the same class; super(...) calls the parent's constructor and must be the first statement in Java.
Pitfall: calling overridable methods from a constructor. The subclass override runs before the subclass fields are initialized.
Destructor
Cleanup when an object is destroyed.
- C++: destructor
~ClassName()runs deterministically when the object goes out of scope. This is the basis of RAII (resource acquisition is initialization): locks, files and sockets are released automatically. - Java: no destructors.
finalize()is deprecated; usetry-with-resourcesandAutoCloseable. - Python:
__del__exists but timing is not guaranteed; use context managers (with).
Access Modifier
Controls who can see a member.
| Modifier (Java) | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
private | Yes | No | No | No |
| default (none) | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public | Yes | Yes | Yes | Yes |
C++ has private, protected, public and friend. Python has no enforced privacy: _name is a convention, __name triggers name mangling.
Rule: make fields private and expose the minimum public surface.
Static Member
Belongs to the class, not to any object. One copy is shared by all instances.
class Counter {
static int created = 0; // shared
Counter() { created++; }
static int total() { return created; }
}- Static methods cannot use
thisor access instance fields directly. - Use for constants, utility functions and factory methods.
- Pitfall: mutable static state is effectively global state; it hurts testing and is a thread-safety risk.
The this keyword
this refers to the current object. Used to disambiguate fields from parameters (this.owner = owner), to pass the current object, and to chain constructors. In Python it is the explicit self parameter.
Getters and Setters
Accessor methods that control reads and writes to private fields. They let a class validate input, compute values lazily, or change its internal representation without breaking callers.
Pitfall: blindly generating a getter and setter for every field gives you a public field with extra steps. Prefer behavior methods like deposit() over setBalance().
Object Equality
| Check | Java | Python | Meaning |
|---|---|---|---|
| Identity | a == b | a is b | Same object in memory |
| Equality | a.equals(b) | a == b | Same logical value |
Override equals and hashCode together: equal objects must have equal hash codes, or hash maps and sets break. See hashing.
Shallow Copy
Copies the object's fields as-is. Referenced objects are shared, so mutating a nested list in the copy also changes the original.
Deep Copy
Recursively copies everything, so the copy is fully independent. More expensive, and tricky with cycles.
import copy
a = {"tags": ["x"]}
s = copy.copy(a) # shallow: s["tags"] is a["tags"]
d = copy.deepcopy(a) # deep: independent listImmutable objects (Java String, Python tuples of immutables) sidestep the problem: sharing them is always safe.
Quick revision
- Class is the blueprint; object is an instance with state, behavior and identity.
- Constructors initialize;
super()first in Java; avoid calling overridable methods in them. - C++ destructors enable RAII; Java uses try-with-resources instead.
- Access: private, default, protected, public; keep fields private.
- Static members belong to the class and are shared; avoid mutable static state.
==is identity in Java,equalsis logical equality; overridehashCodewithequals.- Shallow copy shares nested objects; deep copy duplicates them.