Classes and Objects
Blueprint and instances
Interview Relevant: Fundamental OOP concept
7 min read
Classes and Objects in Java
A class is a blueprint/template that defines structure and behavior. An object is an instance of a class - a real entity with state and behavior.
Class Components
- Fields (Variables): Store object state/data
- Methods: Define object behavior
- Constructors: Initialize objects
- Blocks: Static and instance initializers
- Nested Classes: Classes within classes
🔑 Analogy: Class = Cookie Cutter (template), Object = Cookie (actual instance). One class can create many objects!
💡 Memory: Class is loaded once in Method Area. Each object gets memory in Heap with its own copy of instance variables.
Code Examples
Basic class definition with fields and methods
java
1// Defining a Class
2public class Car {
3 // Fields (instance variables) - state
4 String brand;
5 String color;
6 int speed;
7
8 // Method - behavior
9 public void accelerate() {
10 speed += 10;
11 System.out.println("Speed: " + speed);
12 }
13
14 public void brake() {
15 speed = Math.max(0, speed - 10);
16 System.out.println("Speed: " + speed);
17 }
18
19 public void displayInfo() {
20 System.out.println(brand + " " + color + " at " + speed + " mph");
21 }
22}Creating and using objects
java
1// Creating Objects (Instantiation)
2public class Main {
3 public static void main(String[] args) {
4 // Create object using 'new' keyword
5 Car myCar = new Car();
6
7 // Set field values
8 myCar.brand = "Toyota";
9 myCar.color = "Red";
10 myCar.speed = 0;
11
12 // Call methods
13 myCar.accelerate(); // Speed: 10
14 myCar.accelerate(); // Speed: 20
15 myCar.brake(); // Speed: 10
16 myCar.displayInfo(); // Toyota Red at 10 mph
17
18 // Create another object - independent instance
19 Car otherCar = new Car();
20 otherCar.brand = "Honda";
21 otherCar.color = "Blue";
22 otherCar.speed = 50;
23 otherCar.displayInfo(); // Honda Blue at 50 mph
24
25 // Each object has its own state
26 System.out.println(myCar.speed); // 10
27 System.out.println(otherCar.speed); // 50
28 }
29}Object references and null safety
java
1// Object Reference vs Object
2Car car1 = new Car(); // car1 references an object in heap
3car1.brand = "Tesla";
4
5Car car2 = car1; // car2 references SAME object!
6car2.brand = "BMW";
7
8System.out.println(car1.brand); // BMW (same object!)
9
10// Creating new object
11Car car3 = new Car();
12car3.brand = "Audi";
13
14System.out.println(car1.brand); // BMW
15System.out.println(car3.brand); // Audi (different object)
16
17// Null reference
18Car car4 = null; // Points to nothing
19// car4.brand = "X"; // NullPointerException!
20
21// Checking for null
22if (car4 != null) {
23 car4.accelerate();
24}Well-designed class with encapsulation
java
1// Complete Class Example with Best Practices
2public class BankAccount {
3 // Fields (encapsulated)
4 private String accountNumber;
5 private String holderName;
6 private double balance;
7
8 // Constructor
9 public BankAccount(String accountNumber, String holderName) {
10 this.accountNumber = accountNumber;
11 this.holderName = holderName;
12 this.balance = 0.0;
13 }
14
15 // Getters and Setters
16 public String getAccountNumber() { return accountNumber; }
17 public String getHolderName() { return holderName; }
18 public double getBalance() { return balance; }
19
20 // Business methods
21 public void deposit(double amount) {
22 if (amount > 0) {
23 balance += amount;
24 System.out.println("Deposited: $" + amount);
25 }
26 }
27
28 public boolean withdraw(double amount) {
29 if (amount > 0 && balance >= amount) {
30 balance -= amount;
31 System.out.println("Withdrawn: $" + amount);
32 return true;
33 }
34 System.out.println("Insufficient funds");
35 return false;
36 }
37
38 @Override
39 public String toString() {
40 return "Account: " + accountNumber + ", Holder: " + holderName + ", Balance: $" + balance;
41 }
42}Use Cases
- Modeling real-world entities (User, Product, Order)
- Creating reusable components
- Organizing code logically
- Implementing business logic
- Data encapsulation and protection
- Building complex systems from simple objects
Common Mistakes to Avoid
- Confusing class with object
- Not understanding reference vs object
- Forgetting to instantiate (using null reference)
- Making all fields public (poor encapsulation)
- Creating "God classes" with too many responsibilities
- Not following naming conventions