OOP Fundamentals

Classes and Objects

The fundamental building blocks of Object-Oriented Programming. Everything in OOP revolves around classes (blueprints) and objects (instances).

8 min readEssential

1Understanding with Real-World Analogy

🎯 Real-World Analogy
📐 Class = Blueprint

A class is like an architectural blueprint for a house. It defines:

  • How many rooms (attributes)
  • What color walls (properties)
  • How doors open (methods/behaviors)

But you can't live in a blueprint!

🏠 Object = Actual House

An object is a real house built from the blueprint. It has:

  • Actual paint color: "Blue"
  • Real number of rooms: 3
  • Working doors you can open

Multiple houses can use the same blueprint!

Class → Multiple Objects

CLASS (Blueprint)
Car
color
speed
drive()
🔴
myCar
Red
120 mph
🔵
yourCar
Blue
150 mph
hisCar
Black
200 mph
Class = A template/blueprint that defines attributes (data) and methods (behavior).

Object = An instance of a class with actual values assigned to attributes.

2Anatomy of a Class

Every class consists of these key components:

📦 Attributes (Data/Fields)

Variables that store the state of an object

String name;
int age;
double salary;

⚡ Methods (Behavior/Functions)

Functions that define what an object can do

void walk() {}
String getName() {}
void setAge(int a) {}

🔧 Constructor - Special Method

A constructor is a special method that initializes an object when it's created. It has the same name as the class and no return type.

Default Constructor
No parameters, uses default values
Parameterized Constructor
Takes parameters to set initial values
Copy Constructor
Creates copy from existing object

3Complete Code Example

Let's create a BankAccount class to understand all concepts together:

BankAccount Class - Complete Example
public class BankAccount {
    // ============ ATTRIBUTES (Instance Variables) ============
    private String accountNumber;
    private String holderName;
    private double balance;
    private static int totalAccounts = 0; // Class variable (shared)

    // ============ CONSTRUCTOR (Parameterized) ============
    public BankAccount(String accountNumber, String holderName) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = 0.0;
        totalAccounts++; // Increment class variable
    }

    // ============ METHODS (Behavior) ============
    
    // Deposit money
    public void deposit(double amount) {
        if (amount > 0) {
            this.balance += amount;
            System.out.println("Deposited: $" + amount);
        }
    }

    // Withdraw money
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            this.balance -= amount;
            System.out.println("Withdrawn: $" + amount);
            return true;
        }
        System.out.println("Insufficient balance!");
        return false;
    }

    // Get balance (Getter)
    public double getBalance() {
        return this.balance;
    }

    // Static method - belongs to class, not object
    public static int getTotalAccounts() {
        return totalAccounts;
    }

    // Display account info
    public void displayInfo() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Holder: " + holderName);
        System.out.println("Balance: $" + balance);
    }
}

// ============ CREATING OBJECTS (Main Class) ============
public class Main {
    public static void main(String[] args) {
        // Create objects using 'new' keyword
        BankAccount account1 = new BankAccount("ACC001", "Alice");
        BankAccount account2 = new BankAccount("ACC002", "Bob");

        // Call methods on objects
        account1.deposit(1000);
        account1.withdraw(250);
        account1.displayInfo();

        // Access static method via class name
        System.out.println("Total accounts: " + BankAccount.getTotalAccounts());
    }
}
📤 Output:
Deposited: $1000
Withdrawn: $250
Account: ACC001
Holder: Alice
Balance: $750.0
Total accounts: 2

4Instance vs Static (Class) Members

Understanding the difference between instance and static members is crucial for interviews.

Instance Members

  • Belong to individual objects
  • Each object has its own copy
  • Accessed via object: obj.name
  • Requires object creation
  • Example: accountNumber, balance

Static (Class) Members

  • Belong to the class itself
  • Shared across all objects
  • Accessed via class: Class.name
  • No object needed
  • Example: totalAccounts, getTotalAccounts()

Memory Visualization

CLASS MEMORY (Static)
totalAccounts = 2
account1
accNo = "ACC001"
balance = 750
account2
accNo = "ACC002"
balance = 0

5The 'this' Keyword

this is a reference to the current object. It's used to:
  • Distinguish instance variables from parameters with same name
  • Pass current object to another method
  • Call one constructor from another (constructor chaining)
Using 'this' keyword
public class Person {
    private String name;
    private int age;

    // 'this' distinguishes instance var from parameter
    public Person(String name, int age) {
        this.name = name;  // this.name = instance variable
        this.age = age;    // age = parameter
    }

    // Constructor chaining with this()
    public Person(String name) {
        this(name, 0);  // Calls the 2-param constructor
    }

    // Fluent interface - return this for chaining
    public Person setName(String name) {
        this.name = name;
        return this;  // Enable method chaining
    }

    public Person setAge(int age) {
        this.age = age;
        return this;
    }
}

// Usage with method chaining
Person p = new Person("Alice")
    .setAge(25)
    .setName("Alice Smith");

6Interview Questions

What is the difference between a class and an object?
A class is a blueprint/template that defines attributes and methods. An object is an instance of a class with actual values. Example: 'Car' is a class, 'my red Tesla' is an object.
Can we have multiple constructors in a class?
Yes! This is called constructor overloading. We can have multiple constructors with different parameter lists. Java/C++ support this natively. Python uses default parameters or @classmethod for alternative constructors.
What happens if we don't define a constructor?
The compiler provides a default no-argument constructor that initializes attributes to default values (0, null, false). But if you define ANY constructor, the default is no longer provided automatically.
What is the difference between instance and static methods?
Instance methods belong to objects and can access 'this'/instance variables. Static methods belong to the class, can't access 'this', and can only access other static members. Use static for utility methods that don't need object state.

7Key Takeaways

1Class = Blueprint with attributes (data) and methods (behavior).
2Object = Instance of a class with actual values.
3Constructor initializes objects. Can be overloaded with different parameters.
4Instance members belong to objects; static members belong to the class.
5this/self refers to the current object instance.
6Objects are created using new (Java/C++) or direct call (Python).