Classes and Objects
The fundamental building blocks of Object-Oriented Programming. Everything in OOP revolves around classes (blueprints) and objects (instances).
1Understanding with Real-World Analogy
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!
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
speed
drive()
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
⚡ Methods (Behavior/Functions)
Functions that define what an object can do
🔧 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.
3Complete Code Example
Let's create a BankAccount class to understand all concepts together:
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());
}
}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
5The 'this' Keyword
- Distinguish instance variables from parameters with same name
- Pass current object to another method
- Call one constructor from another (constructor chaining)
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
7Key Takeaways
new (Java/C++) or direct call (Python).