OOP Notes
Master the fundamental building blocks of OOP — understand what classes and objects are, how to define them, and how they work together to model real-world entities.
## What is an Object?
An **object** is a specific instance of a class. When you create an object, memory is allocated to store its attributes, and you can call its methods. Each object has its own independent copy of the class's attributes.public class Main { public static void main(String[] args) { // Creating objects (instances) from the Car class Car myCar = new Car("Toyota", "Camry", 2023); Car friendsCar = new Car("Honda", "Civic", 2022);
// Each object has its own state myCar.startEngine(); // Toyota Camry engine started! myCar.drive(50); // Drove 50 km. Fuel remaining: 95.0%
friendsCar.startEngine(); // Honda Civic engine started! friendsCar.drive(100); // Drove 100 km. Fuel remaining: 90.0%
// myCar's fuel is unaffected by friendsCar's driving System.out.println(myCar.fuelLevel); // 95.0 System.out.println(friendsCar.fuelLevel); // 90.0 } }
CLASS (Blueprint) OBJECTS (Instances) ┌─────────────────┐ ┌─────────────────┐ │ Car │ │ myCar │ │ │ ──────> │ make: "Toyota" │ │ - make │ │ model: "Camry" │ │ - model │ │ year: 2023 │ │ - year │ │ fuel: 95.0 │ │ - fuelLevel │ └─────────────────┘ │ │ │ + startEngine() │ ──────> ┌─────────────────┐ │ + drive() │ │ friendsCar │ │ + stopEngine() │ │ make: "Honda" │ └─────────────────┘ │ model: "Civic" │ │ year: 2022 │ │ fuel: 90.0 │ └─────────────────┘
class BankAccount: """A simple bank account class"""
def __init__(self, owner, balance=0): """Constructor — called when creating a new account""" self.owner = owner self.balance = balance self.transactions = []
def deposit(self, amount): """Add money to the account""" if amount <= 0: print("Deposit amount must be positive") return self.balance += amount self.transactions.append(f"+${amount}") print(f"Deposited ${amount}. New balance: ${self.balance}")
def withdraw(self, amount): """Remove money from the account""" if amount <= 0: print("Withdrawal amount must be positive") return if amount > self.balance: print(f"Insufficient funds. Balance: ${self.balance}") return self.balance -= amount self.transactions.append(f"-${amount}") print(f"Withdrew ${amount}. New balance: ${self.balance}")
def get_statement(self): """Print transaction history""" print(f"\n--- Statement for {self.owner} ---") for t in self.transactions: print(f" {t}") print(f" Current balance: ${self.balance}") print("---")
alice_account = BankAccount("Alice", 1000) bob_account = BankAccount("Bob", 500)
Using objects
alice_account.deposit(200) # Deposited $200. New balance: $1200 alice_account.withdraw(50) # Withdrew $50. New balance: $1150 bob_account.deposit(300) # Deposited $300. New balance: $800 alice_account.get_statement()
#include <iostream> #include <string> #include <vector>
class Student { private: std::string name; int id; std::vector<double> grades;
public: // Constructor Student(std::string name, int id) : name(name), id(id) {}
void addGrade(double grade) { if (grade >= 0 && grade <= 100) { grades.push_back(grade); } }
double getGPA() const { if (grades.empty()) return 0.0; double sum = 0; for (double g : grades) sum += g; return sum / grades.size(); }
void display() const { std::cout << "Student: " << name << " (ID: " << id << ")" << " GPA: " << getGPA() << std::endl; } };
int main() { Student s1("Alice", 1001); Student s2("Bob", 1002);
s1.addGrade(95); s1.addGrade(87); s2.addGrade(72); s2.addGrade(85);
s1.display(); // Student: Alice (ID: 1001) GPA: 91 s2.display(); // Student: Bob (ID: 1002) GPA: 78.5 return 0; }
Car car1 = new Car("Toyota", "Camry", 2023); Car car2 = new Car("Toyota", "Camry", 2023);
// Same state, but different identity System.out.println(car1 == car2); // false — different objects in memory System.out.println(car1.equals(car2)); // depends on equals() implementation
## Common Mistakes
1. **Confusing class with object** — the class is the template, the object is the instance
2. **Forgetting that objects are independent** — changing one object doesn't affect another (unless they share references)
3. **Making everything public** — attributes should usually be private with controlled access
4. **Not initializing attributes** — always set sensible defaults in constructors
5. **Creating God classes** — one class shouldn't do everything; keep classes focused
## Key Takeaways
- A **class** defines the structure and behavior; an **object** is a concrete instance
- You can create many objects from one class, each with its own state
- Objects encapsulate both data (attributes) and behavior (methods)
- Classes model real-world entities or abstract concepts
- Every object has identity (unique reference), state (attribute values), and behavior (methods)
- Good class design is the foundation of good OOP — get this right, and everything else followsExam Focus
Revise definitions, diagrams, examples, and short-answer points for Classes and Objects.
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, classes
Related Object Oriented Programming (OOP) Topics