Programming in Java

Unit 6: OOP — Classes, Objects & Constructors

From blueprint to living object — master classes, constructors, method overloading, and the this keyword to build real-world Java applications.

⏱️ Time: 7 hrs theory + 5 hrs lab  |  💰 Earning: ₹8K–₹25K/month  |  📝 30 MCQs (Bloom's Mapped)

💼 Jobs: Java Developer (₹4–8 LPA)  |  Android Developer (₹5–10 LPA)  |  Backend Engineer (₹6–12 LPA)

Section A

Opening Hook — Every Zomato Order Is an Object

🍕 When You Tap "Order Now," Java Creates an Object

Every time you place a Zomato order, a Java object springs to life. It has fields: orderId, restaurant, items[], status, deliveryAddress. It has methods: placeOrder(), cancelOrder(), trackDelivery(). When you tap "Order Now," the backend calls new ZomatoOrder() — a constructor fires, initialises every field, and the status changes from CREATED → PLACED → PREPARING → OUT_FOR_DELIVERY → DELIVERED.

Zomato's backend runs on Java microservices processing 2 million+ orders per day. Each order = 1 object. Each restaurant = 1 object. Each delivery partner = 1 object. At peak hours during IPL nights, Zomato creates 40,000+ order objects per minute. OOP isn't abstract textbook theory — it's the architecture of every app on your phone.

What if YOU had built this? What if you could design a ZomatoOrder class with constructors, methods, and proper encapsulation? That's exactly what this chapter teaches you — from blueprint to living, breathing Java objects.

🇮🇳 Zomato🇮🇳 Flipkart🇮🇳 Ola🇮🇳 Swiggy🇮🇳 Paytm🇮🇳 PhonePe
Java powers 3 billion+ devices worldwide. 90% of Fortune 500 companies use Java for backend systems. India has 12 million+ Java developers — the largest Java developer community in the world. Every Android app, every banking NEFT/RTGS transaction, every Aadhaar authentication runs on Java. Learning OOP in Java isn't just academics — it's your career ticket.
Section B

Learning Outcomes — Bloom's Taxonomy Mapped

Bloom's LevelLearning Outcome
🔵 RememberDefine class, object, constructor, method, and the this keyword with correct Java syntax
🔵 RememberList the 5 uses of the this keyword and 3 types of constructors in Java
🔵 UnderstandExplain the difference between class and object using the DDA flat blueprint analogy
🔵 UnderstandDescribe how constructor chaining works using this() and super()
🟢 ApplyWrite a BankAccount class with parameterized constructor, deposit(), withdraw(), and getBalance()
🟢 ApplyImplement constructor overloading with default, parameterized, and copy constructors
🟢 AnalyzeDifferentiate between instance methods and static methods with real code examples
🟢 AnalyzeCompare method overloading vs method overriding (preview for Unit 7)
🟠 EvaluateDebug constructor chaining errors and predict output of complex this() calls
🟠 EvaluateAssess when to use static methods vs instance methods in application design
🟠 CreateDesign a complete ZomatoOrder class with multiple constructors and business logic methods
🟠 CreateBuild a StudentRecord management system with proper OOP encapsulation
Section C

Concept Explanation — OOP from Scratch

1. Class vs Object — The Blueprint Analogy

Imagine the DDA (Delhi Development Authority) designs a blueprint for a 2BHK flat. The blueprint specifies: 2 bedrooms, 1 kitchen, 1 bathroom, 1 balcony, total area = 850 sq ft. This blueprint is the class. Now DDA builds 500 actual flats from this blueprint in Dwarka. Each flat has a unique flat number, different paint colours, different furniture — but the structure is the same. Each flat is an object.

📐 Class vs Object — Core Differences

AspectClassObject
DefinitionA blueprint/template for creating objectsAn instance of a class — a real entity in memory
MemoryNo memory allocated when class is definedMemory allocated when object is created with new
ExistenceLogical — exists in code onlyPhysical — exists in heap memory at runtime
CreatedUsing the class keywordUsing the new keyword
AnalogyDDA flat blueprintActual flat in Dwarka (Flat #301, #302…)
CountDefined onceMany objects can be created from one class

Syntax — Defining a class and creating objects:

Java
// Class definition — the blueprint
class Student {
    // Fields (instance variables)
    String name;
    int rollNo;
    double marks;

    // Method
    void display() {
        System.out.println(name + " | Roll: " + rollNo + " | Marks: " + marks);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating objects — building flats from blueprint
        Student s1 = new Student();
        s1.name = "Aarav";
        s1.rollNo = 101;
        s1.marks = 92.5;

        Student s2 = new Student();
        s2.name = "Priya";
        s2.rollNo = 102;
        s2.marks = 88.0;

        s1.display();
        s2.display();
    }
}
Aarav | Roll: 101 | Marks: 92.5 Priya | Roll: 102 | Marks: 88.0
Every Flipkart product listing is a Java object. Flipkart has a Product class with fields like productId, title, price, seller, rating. When you search "blue shirt," the backend creates thousands of Product objects from the database. Each object has methods like addToCart(), addToWishlist(), calculateDiscount(). OOP runs the ₹10,000+ crore marketplace.

2. Writing Classes in Java

A well-written Java class has a clear anatomy: access modifier, class keyword, class name (PascalCase), fields, constructors, and methods.

🏗️ Anatomy of a Java Class

Naming Conventions:

• Class names → PascalCase: BankAccount, StudentRecord, ZomatoOrder

• Method/variable names → camelCase: getBalance(), accountNumber, holderName

• Constants → UPPER_SNAKE_CASE: MAX_BALANCE, MIN_AGE

Full BankAccount Class:

Java
public class BankAccount {
    // Fields (private for encapsulation)
    private String accountNumber;
    private String holderName;
    private double balance;
    private String ifscCode;

    // Parameterized Constructor
    public BankAccount(String accountNumber, String holderName,
                       double initialDeposit, String ifscCode) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = initialDeposit;
        this.ifscCode = ifscCode;
    }

    // Deposit method
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("₹" + amount + " deposited. New Balance: ₹" + balance);
        } else {
            System.out.println("Invalid deposit amount!");
        }
    }

    // Withdraw method
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("₹" + amount + " withdrawn. Remaining: ₹" + balance);
        } else {
            System.out.println("Insufficient balance or invalid amount!");
        }
    }

    // Display method
    public void displayDetails() {
        System.out.println("A/C: " + accountNumber + " | Name: " + holderName);
        System.out.println("Balance: ₹" + balance + " | IFSC: " + ifscCode);
    }

    public double getBalance() {
        return balance;
    }
}

public class BankDemo {
    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount("SBI-10042", "Rahul Verma", 50000, "SBIN0001234");
        acc1.displayDetails();
        acc1.deposit(15000);
        acc1.withdraw(8000);
        System.out.println("Final Balance: ₹" + acc1.getBalance());
    }
}
A/C: SBI-10042 | Name: Rahul Verma Balance: ₹50000.0 | IFSC: SBIN0001234 ₹15000.0 deposited. New Balance: ₹65000.0 ₹8000.0 withdrawn. Remaining: ₹57000.0 Final Balance: ₹57000.0

3. Constructors — Default, Parameterized & Copy

A constructor is a special method that runs automatically when you create an object with new. It has the same name as the class and no return type (not even void). Its job is to initialise the object's fields.

🔧 3 Types of Constructors

TypeDescriptionWhen to Use
DefaultNo parameters. Sets default values.When you want a "blank" object with sensible defaults
ParameterizedTakes parameters to initialise fields.When you know all values at creation time
CopyTakes an object of the same class. Copies its values.When you want a duplicate/clone (e.g., Zomato "Reorder")

Full StudentRecord class with all 3 constructors:

Java
public class StudentRecord {
    String name;
    int rollNo;
    String branch;
    double cgpa;

    // 1. Default Constructor
    public StudentRecord() {
        this.name = "Unknown";
        this.rollNo = 0;
        this.branch = "Not Assigned";
        this.cgpa = 0.0;
        System.out.println("Default constructor called");
    }

    // 2. Parameterized Constructor
    public StudentRecord(String name, int rollNo, String branch, double cgpa) {
        this.name = name;
        this.rollNo = rollNo;
        this.branch = branch;
        this.cgpa = cgpa;
        System.out.println("Parameterized constructor called");
    }

    // 3. Copy Constructor
    public StudentRecord(StudentRecord other) {
        this.name = other.name;
        this.rollNo = other.rollNo;
        this.branch = other.branch;
        this.cgpa = other.cgpa;
        System.out.println("Copy constructor called");
    }

    void display() {
        System.out.println(name + " | " + rollNo + " | " + branch + " | CGPA: " + cgpa);
    }

    public static void main(String[] args) {
        StudentRecord s1 = new StudentRecord();
        s1.display();

        StudentRecord s2 = new StudentRecord("Ananya", 201, "CSE", 9.2);
        s2.display();

        StudentRecord s3 = new StudentRecord(s2);  // copy of s2
        s3.display();
    }
}
Default constructor called Unknown | 0 | Not Assigned | CGPA: 0.0 Parameterized constructor called Ananya | 201 | CSE | CGPA: 9.2 Copy constructor called Ananya | 201 | CSE | CGPA: 9.2
If you write ANY constructor, Java stops providing the default constructor. If you only write a parameterized constructor, then new StudentRecord() will give a compilation error! You must explicitly write the default constructor too if you need both.
Java does NOT have a built-in copy constructor like C++. You have to write it yourself. But it's a common interview question and very useful in real projects — e.g., Zomato's "Reorder" feature creates a copy of the previous order object.

4. Constructor Overloading

Constructor overloading means having multiple constructors in the same class with different parameter lists. Java decides which constructor to call based on the arguments you pass to new.

Java
public class Product {
    String name;
    double price;
    String category;
    int quantity;

    // Constructor 1: No arguments
    public Product() {
        this.name = "Generic Product";
        this.price = 0.0;
        this.category = "General";
        this.quantity = 1;
    }

    // Constructor 2: Name and price
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
        this.category = "General";
        this.quantity = 1;
    }

    // Constructor 3: Name, price, category
    public Product(String name, double price, String category) {
        this.name = name;
        this.price = price;
        this.category = category;
        this.quantity = 1;
    }

    // Constructor 4: All fields
    public Product(String name, double price, String category, int quantity) {
        this.name = name;
        this.price = price;
        this.category = category;
        this.quantity = quantity;
    }

    void display() {
        System.out.println(name + " | ₹" + price + " | " + category + " | Qty: " + quantity);
    }

    public static void main(String[] args) {
        Product p1 = new Product();
        Product p2 = new Product("Notebook", 45.0);
        Product p3 = new Product("Pen", 10.0, "Stationery");
        Product p4 = new Product("Eraser", 5.0, "Stationery", 10);

        p1.display();
        p2.display();
        p3.display();
        p4.display();
    }
}
Generic Product | ₹0.0 | General | Qty: 1 Notebook | ₹45.0 | General | Qty: 1 Pen | ₹10.0 | Stationery | Qty: 1 Eraser | ₹5.0 | Stationery | Qty: 10

5. Constructor Chaining — this()

Constructor chaining means calling one constructor from another constructor within the same class using this(). This avoids code duplication — instead of repeating initialisation logic in every constructor, you chain them.

Java
public class Employee {
    String name;
    int empId;
    String department;
    double salary;

    // Constructor 1: All fields (master constructor)
    public Employee(String name, int empId, String department, double salary) {
        this.name = name;
        this.empId = empId;
        this.department = department;
        this.salary = salary;
        System.out.println("Master constructor called");
    }

    // Constructor 2: Chains to Constructor 1
    public Employee(String name, int empId, String department) {
        this(name, empId, department, 25000.0);  // chain → default salary
        System.out.println("3-param constructor called");
    }

    // Constructor 3: Chains to Constructor 2
    public Employee(String name, int empId) {
        this(name, empId, "General");  // chain → default department
        System.out.println("2-param constructor called");
    }

    // Constructor 4: Chains to Constructor 3
    public Employee() {
        this("New Employee", 0);  // chain → default name & id
        System.out.println("Default constructor called");
    }

    void display() {
        System.out.println(name + " | ID: " + empId + " | " + department + " | ₹" + salary);
    }

    public static void main(String[] args) {
        System.out.println("--- Creating default employee ---");
        Employee e1 = new Employee();
        e1.display();
    }
}
--- Creating default employee --- Master constructor called 3-param constructor called 2-param constructor called Default constructor called New Employee | ID: 0 | General | ₹25000.0
this() must be the FIRST statement in the constructor. You cannot write any code before this(). Also, you CANNOT have both this() and super() in the same constructor — only one is allowed, and it must be first.

6. Methods — Instance vs Static

Methods define the behaviour of objects. There are two types:

AspectInstance MethodStatic Method
Belongs toObject (instance)Class itself
Called viaobjectName.method()ClassName.method()
AccessCan access instance + static variablesCan access static variables ONLY
this keyword✅ Available❌ Not available
Exampleacc.deposit(5000)Math.sqrt(25)
MemoryNeeds object to be created firstAvailable even without any object
Java
public class Counter {
    // Instance variable — each object gets its own copy
    int instanceCount = 0;

    // Static variable — shared among ALL objects
    static int totalCount = 0;

    // Instance method
    void increment() {
        instanceCount++;
        totalCount++;
    }

    // Static method
    static void showTotal() {
        System.out.println("Total across all objects: " + totalCount);
        // System.out.println(instanceCount); ❌ ERROR — can't access instance var
    }

    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();

        c1.increment();
        c1.increment();
        c2.increment();

        System.out.println("c1 instance count: " + c1.instanceCount);
        System.out.println("c2 instance count: " + c2.instanceCount);
        Counter.showTotal();
    }
}
c1 instance count: 2 c2 instance count: 1 Total across all objects: 3
Use static methods for utility functions that don't need object state. Examples: Math.pow(), Integer.parseInt(), Collections.sort(). The main() method itself is static — because JVM needs to call it before any object exists.

7. Method Overloading

Method overloading means having multiple methods with the same name but different parameter lists (different number, type, or order of parameters). The return type alone is NOT sufficient for overloading.

Java
public class Calculator {
    // Overloaded add() — 4 versions

    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }

    double add(double a, double b) {
        return a + b;
    }

    String add(String a, String b) {
        return a + b;  // String concatenation
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(10, 20));
        System.out.println(calc.add(10, 20, 30));
        System.out.println(calc.add(3.5, 4.5));
        System.out.println(calc.add("Edu", "Artha"));
    }
}
30 60 8.0 EduArtha
You CANNOT overload by return type alone. int add(int a, int b) and double add(int a, int b) will cause a compilation error — Java cannot decide which to call just by looking at arguments. Parameters must differ.

8. The this Keyword — 5 Uses

The this keyword is a reference to the current object — the object on which the method is being called. It has 5 distinct uses:

🔑 5 Uses of the this Keyword

Use 1: Distinguish instance variable from parameter

Java
public Student(String name, int rollNo) {
    this.name = name;      // this.name → field, name → parameter
    this.rollNo = rollNo;
}

Use 2: Call another constructor — this()

Java
public Student() {
    this("Unknown", 0);  // calls parameterized constructor
}

Use 3: Pass current object as argument

Java
void enroll(Course course) {
    course.addStudent(this);  // pass this Student object to the course
}

Use 4: Return current object (method chaining)

Java
Student setName(String name) {
    this.name = name;
    return this;  // enables: s.setName("A").setRoll(1)
}

Use 5: Refer to current object in inner class

Java
class Outer {
    int x = 10;
    class Inner {
        int x = 20;
        void show() {
            System.out.println(this.x);        // 20 — Inner's x
            System.out.println(Outer.this.x);  // 10 — Outer's x
        }
    }
}

Full example combining multiple uses:

Java
public class Pizza {
    String size;
    String crust;
    String topping;

    public Pizza() {
        this("Medium", "Thin", "Cheese");  // Use 2: this()
    }

    public Pizza(String size, String crust, String topping) {
        this.size = size;       // Use 1: this.field
        this.crust = crust;
        this.topping = topping;
    }

    Pizza setSize(String size) {
        this.size = size;
        return this;  // Use 4: return this for chaining
    }

    Pizza setCrust(String crust) {
        this.crust = crust;
        return this;
    }

    Pizza setTopping(String topping) {
        this.topping = topping;
        return this;
    }

    void display() {
        System.out.println(size + " | " + crust + " | " + topping);
    }

    public static void main(String[] args) {
        // Method chaining using return this
        Pizza myPizza = new Pizza()
            .setSize("Large")
            .setCrust("Stuffed")
            .setTopping("Paneer Tikka");
        myPizza.display();
    }
}
Large | Stuffed | Paneer Tikka

9. Initializer Blocks

Java has two types of initializer blocks that run before or during object creation:

TypeSyntaxWhen It RunsUse Case
Static Blockstatic { ... }Once — when class is first loadedDatabase connection, loading config
Instance Block{ ... }Every time an object is created (before constructor)Common init for all constructors
Java
public class InitDemo {
    int x;

    // Static initializer block — runs ONCE when class loads
    static {
        System.out.println("1. Static block executed");
    }

    // Instance initializer block — runs EVERY TIME before constructor
    {
        x = 10;
        System.out.println("2. Instance block executed (x = " + x + ")");
    }

    // Constructor
    public InitDemo() {
        x = 20;
        System.out.println("3. Constructor executed (x = " + x + ")");
    }

    public static void main(String[] args) {
        System.out.println("--- Creating first object ---");
        InitDemo obj1 = new InitDemo();
        System.out.println("--- Creating second object ---");
        InitDemo obj2 = new InitDemo();
    }
}
1. Static block executed --- Creating first object --- 2. Instance block executed (x = 10) 3. Constructor executed (x = 20) --- Creating second object --- 2. Instance block executed (x = 10) 3. Constructor executed (x = 20)
Order of execution: Static block (once) → Instance block (every time) → Constructor (every time). This is a favourite interview question. Memorise this order!

10. Access Modifiers in OOP

ModifierSame ClassSame PackageSubclass (other pkg)Other Package
public
protected
default (no keyword)
private

Encapsulation pattern — private fields + public getters/setters:

Java
public class AadhaarCard {
    private String aadhaarNumber;  // private — no direct access
    private String holderName;

    public AadhaarCard(String aadhaarNumber, String holderName) {
        this.aadhaarNumber = aadhaarNumber;
        this.holderName = holderName;
    }

    // Public getter — controlled read access
    public String getMaskedAadhaar() {
        return "XXXX-XXXX-" + aadhaarNumber.substring(8);
    }

    // Public getter
    public String getHolderName() {
        return holderName;
    }

    // No setter for aadhaarNumber — it should never change!
}
Aadhaar's security depends on encapsulation. The UIDAI system stores biometric data in private fields. No external system can directly read your fingerprints — they go through authenticated public API methods. This is real-world encapsulation at national scale protecting 1.4 billion Indians' data.

11. Object Lifecycle

♻️ Life of a Java Object

Stage 1 — Creation: Student s = new Student();

• The new keyword allocates memory on the heap

• The constructor initialises the object's fields

• A reference (s) is stored on the stack pointing to the heap object

Stage 2 — Usage:

• Call methods: s.display();

• Access/modify fields: s.name = "Aarav";

• Pass to other methods: printStudent(s);

Stage 3 — Eligible for Garbage Collection:

• When no reference points to the object: s = null;

• When the reference goes out of scope (method ends)

• When the reference is reassigned: s = new Student(); (old object is orphaned)

Stage 4 — Garbage Collection:

• JVM's garbage collector automatically reclaims memory

finalize() method (deprecated since Java 9) may be called before destruction

• You CANNOT force garbage collection — System.gc() is only a suggestion

Java handles memory management for you — unlike C/C++ where you must manually free memory. This is one of Java's biggest advantages. No memory leaks from forgetting to call free(). The garbage collector runs in the background, quietly cleaning up unused objects.

12. Full Industry Code — ZomatoOrder Class

Java
public class ZomatoOrder {
    private String orderId;
    private String customerName;
    private String restaurant;
    private String[] items;
    private double totalAmount;
    private String status;
    private String deliveryAddress;
    private static int orderCount = 0;

    // Default Constructor
    public ZomatoOrder() {
        orderCount++;
        this.orderId = "ZMT-" + System.currentTimeMillis();
        this.status = "CREATED";
    }

    // Parameterized Constructor — chains to default
    public ZomatoOrder(String customerName, String restaurant,
                       String[] items, double totalAmount, String deliveryAddress) {
        this();  // Constructor chaining!
        this.customerName = customerName;
        this.restaurant = restaurant;
        this.items = items;
        this.totalAmount = totalAmount;
        this.deliveryAddress = deliveryAddress;
    }

    // Copy Constructor (for reorder feature)
    public ZomatoOrder(ZomatoOrder previousOrder) {
        this();  // new orderId & status
        this.customerName = previousOrder.customerName;
        this.restaurant = previousOrder.restaurant;
        this.items = previousOrder.items.clone();
        this.totalAmount = previousOrder.totalAmount;
        this.deliveryAddress = previousOrder.deliveryAddress;
    }

    // Place order
    public void placeOrder() {
        if (items != null && items.length > 0) {
            this.status = "PLACED";
            System.out.println("✅ Order " + orderId + " placed at " + restaurant);
            System.out.println("   Items: " + String.join(", ", items));
            System.out.println("   Total: ₹" + totalAmount);
        } else {
            System.out.println("❌ Cannot place order — no items!");
        }
    }

    // Overloaded placeOrder with delivery instructions
    public void placeOrder(String instructions) {
        placeOrder();
        System.out.println("   Instructions: " + instructions);
    }

    // Cancel order
    public void cancelOrder() {
        if (status.equals("PLACED") || status.equals("CREATED")) {
            this.status = "CANCELLED";
            System.out.println("🚫 Order " + orderId + " cancelled. Refund: ₹" + totalAmount);
        } else {
            System.out.println("❌ Cannot cancel — order is " + status);
        }
    }

    // Track delivery
    public void trackDelivery() {
        System.out.println("📍 Order: " + orderId + " | Status: " + status);
        System.out.println("   Delivering to: " + deliveryAddress);
    }

    // Display order summary
    public void displayOrderSummary() {
        System.out.println("===== ORDER SUMMARY =====");
        System.out.println("Order ID    : " + orderId);
        System.out.println("Customer    : " + customerName);
        System.out.println("Restaurant  : " + restaurant);
        System.out.println("Items       : " + String.join(", ", items));
        System.out.println("Amount      : ₹" + totalAmount);
        System.out.println("Status      : " + status);
        System.out.println("Address     : " + deliveryAddress);
        System.out.println("=========================");
    }

    // Static method — total orders
    public static int getOrderCount() {
        return orderCount;
    }
}

public class ZomatoDemo {
    public static void main(String[] args) {
        // Create an order
        String[] items1 = {"Butter Chicken", "Naan", "Dal Makhani"};
        ZomatoOrder order1 = new ZomatoOrder(
            "Aarav Sharma", "Punjab Grill", items1, 850.0, "Sector 21, Dwarka, Delhi"
        );

        order1.placeOrder("Extra butter in naan please");
        order1.trackDelivery();

        // Reorder using copy constructor
        System.out.println("\n--- REORDER ---");
        ZomatoOrder reorder = new ZomatoOrder(order1);
        reorder.placeOrder();
        reorder.displayOrderSummary();

        System.out.println("\nTotal orders today: " + ZomatoOrder.getOrderCount());
    }
}
✅ Order ZMT-1719100000001 placed at Punjab Grill Items: Butter Chicken, Naan, Dal Makhani Total: ₹850.0 Instructions: Extra butter in naan please 📍 Order: ZMT-1719100000001 | Status: PLACED Delivering to: Sector 21, Dwarka, Delhi --- REORDER --- ✅ Order ZMT-1719100000002 placed at Punjab Grill Items: Butter Chicken, Naan, Dal Makhani Total: ₹850.0 ===== ORDER SUMMARY ===== Order ID : ZMT-1719100000002 Customer : Aarav Sharma Restaurant : Punjab Grill Items : Butter Chicken, Naan, Dal Makhani Amount : ₹850.0 Status : PLACED Address : Sector 21, Dwarka, Delhi ========================= Total orders today: 2
Section D

Learn by Doing — 3-Tier Lab Structure

🟢 Tier 1 — GUIDED TASK: Build a Basic ZomatoOrder Class

⏱️ 45–60 minutesBeginnerStep-by-step instructions

Step 1: Create the class with fields

Create a file ZomatoOrder.java. Define the class with these fields: orderId (String), customerName (String), restaurant (String), items (String[]), totalAmount (double), status (String).

Step 2: Add a default constructor

Write a constructor with no parameters. Set orderId to "ZMT-001", status to "CREATED", and all other fields to defaults.

Step 3: Add a parameterized constructor

Write a constructor that takes customerName, restaurant, items[], and totalAmount. Use this() to chain to the default constructor for orderId and status.

Step 4: Add methods

Write placeOrder() — sets status to "PLACED" and prints order details.

Write cancelOrder() — sets status to "CANCELLED" if currently "PLACED".

Write display() — prints all fields.

Step 5: Write the main method

Java
public class ZomatoOrderTier1 {
    String orderId;
    String customerName;
    String restaurant;
    String[] items;
    double totalAmount;
    String status;

    // Default Constructor
    public ZomatoOrderTier1() {
        this.orderId = "ZMT-001";
        this.status = "CREATED";
        this.customerName = "Guest";
        this.restaurant = "Unknown";
        this.items = new String[]{};
        this.totalAmount = 0.0;
    }

    // Parameterized Constructor
    public ZomatoOrderTier1(String customerName, String restaurant,
                            String[] items, double totalAmount) {
        this();  // chain to default
        this.customerName = customerName;
        this.restaurant = restaurant;
        this.items = items;
        this.totalAmount = totalAmount;
    }

    void placeOrder() {
        this.status = "PLACED";
        System.out.println("Order " + orderId + " placed at " + restaurant);
        for (String item : items) {
            System.out.println("  - " + item);
        }
        System.out.println("Total: ₹" + totalAmount);
    }

    void cancelOrder() {
        if (status.equals("PLACED")) {
            this.status = "CANCELLED";
            System.out.println("Order " + orderId + " cancelled.");
        } else {
            System.out.println("Cannot cancel — status is " + status);
        }
    }

    void display() {
        System.out.println("ID: " + orderId + " | Customer: " + customerName +
                           " | Restaurant: " + restaurant + " | Status: " + status);
    }

    public static void main(String[] args) {
        String[] myItems = {"Paneer Tikka", "Garlic Naan", "Lassi"};
        ZomatoOrderTier1 order = new ZomatoOrderTier1("Ravi Kumar", "Bikanervala", myItems, 520.0);
        order.placeOrder();
        order.display();
        order.cancelOrder();
        order.display();
    }
}
Order ZMT-001 placed at Bikanervala - Paneer Tikka - Garlic Naan - Lassi Total: ₹520.0 ID: ZMT-001 | Customer: Ravi Kumar | Restaurant: Bikanervala | Status: PLACED Order ZMT-001 cancelled. ID: ZMT-001 | Customer: Ravi Kumar | Restaurant: Bikanervala | Status: CANCELLED

🎉 Congratulations! You've built your first OOP class with constructors and methods!

🟡 Tier 2 — SEMI-GUIDED: Extend with Constructor Overloading & Static Methods

⏱️ 60–90 minutesIntermediateHints provided, you fill the gaps

Your Mission:

Extend the Tier 1 ZomatoOrder class with these features:

  1. Copy Constructor: Add a constructor that takes another ZomatoOrder object and creates a "Reorder" (new orderId, same items)
  2. Overloaded placeOrder(): Add a version that accepts String deliveryInstructions
  3. Static field orderCount: Track total orders created across all objects
  4. Static method getOrderCount(): Return total order count
  5. Method chaining: Make setCustomerName(), setRestaurant() return this
Stretch Goal: Add an applyDiscount(double percent) method and a calculateGST() method that adds 5% GST. Chain them: order.applyDiscount(10).calculateGST().placeOrder();

🔴 Tier 3 — OPEN CHALLENGE: Restaurant Management System

⏱️ 2–3 hoursAdvancedNo instructions — real-world mini-project

The Brief:

Design a complete Restaurant Management System with these classes:

  1. MenuItem — name, price, category (veg/non-veg), isAvailable. Overloaded constructors.
  2. Restaurant — name, location, rating, menu (array of MenuItem). Methods: addItem(), removeItem(), displayMenu().
  3. ZomatoOrder — extends Tier 2 class. Adds delivery time estimation.
  4. DeliveryPartner — name, vehicleType, isAvailable, rating. Methods: acceptDelivery(), completeDelivery().

Requirements:

• Use constructor chaining and overloading in every class

• Use this keyword in all 5 ways

• Have at least 2 static methods and 1 static variable

• Demonstrate method overloading in at least 2 classes

This project structure is used in real Zomato/Swiggy backend codebases. Complete it, push to GitHub, and mention it in your resume. Interviewers love seeing real OOP projects.
Section E

Problem Set — Syntax, Programming & Industry

Syntax / Trace Questions (5)

Q1. What is the output?

Java
class Chain {
    Chain() { this(10); System.out.println("A"); }
    Chain(int x) { this(10, 20); System.out.println("B" + x); }
    Chain(int x, int y) { System.out.println("C" + (x+y)); }
}
// new Chain(); prints → ?

Answer: C30, B10, A (constructors chain bottom-up, then print top-down on return)

Q2. Find the error:

Java
class Box {
    int length, width;
    Box(int length, int width) {
        length = length;  // ← WHAT'S WRONG?
        width = width;
    }
}

Answer: Missing this. — the parameters shadow the fields. Should be this.length = length; and this.width = width;. Without this, the parameter is assigned to itself, and the field remains 0.

Q3. What is the output?

Java
class Overload {
    void show(int a) { System.out.println("int: " + a); }
    void show(double a) { System.out.println("double: " + a); }
    void show(String a) { System.out.println("String: " + a); }
}
// new Overload().show(5);      → ?
// new Overload().show(5.5);    → ?
// new Overload().show("five"); → ?

Answer: int: 5, double: 5.5, String: five — Java resolves by matching argument type to parameter type.

Q4. Find the error:

Java
class Test {
    int x;
    Test() {
        System.out.println("Hello");
        this(10);  // ← WHAT'S WRONG?
    }
    Test(int x) { this.x = x; }
}

Answer: this() must be the first statement in the constructor. System.out.println("Hello") comes before this(10), causing a compilation error.

Q5. What is the output?

Java
class Demo {
    static int count = 0;
    int id;
    Demo() { count++; id = count; }
    static void showCount() { System.out.println("Count: " + count); }
    void showId() { System.out.println("ID: " + id); }
}
// Demo d1 = new Demo(); Demo d2 = new Demo(); Demo d3 = new Demo();
// d2.showId(); Demo.showCount(); → ?

Answer: ID: 2, Count: 3 — static count is shared; d2 was created second (id=2); after d3, count=3.

Programming Questions (8)

P1. Write a Rectangle class with fields length and width, a parameterized constructor, and methods area() and perimeter(). Create 2 Rectangle objects and display their areas.

P2. Create a Book class with fields title, author, price, isbn. Write 3 overloaded constructors: (i) no parameters (ii) title + author (iii) all fields. Test all three.

P3. Implement method chaining in a PizzaBuilder class. Methods setSize(), setCrust(), addTopping() should return this. Final call: new PizzaBuilder().setSize("Large").setCrust("Stuffed").addTopping("Mushroom").build();

P4. Write a Student class with a static field totalStudents. Every time a Student is created, increment the counter. Add a static method getTotalStudents(). Create 5 students and print the total.

P5. Create a Time class with constructor overloading: (i) Time() → 00:00:00 (ii) Time(int hours) → hh:00:00 (iii) Time(int hours, int minutes) → hh:mm:00 (iv) Time(int hours, int minutes, int seconds) → hh:mm:ss. Use constructor chaining.

P6. Write an Employee class demonstrating all 5 uses of the this keyword in a single class.

P7. Build a Calculator class with 4 overloaded multiply() methods: (i) two ints (ii) three ints (iii) two doubles (iv) int and double.

P8. Create a MobilePhone class with fields brand, model, price, ram. Write a copy constructor. Create a phone object for "Samsung Galaxy S24" and clone it for "Samsung Galaxy S24 Ultra" (change only model and price).

Industry Questions — Ola Driver Class (3)

🚗 Ola Driver System Design

I1. Design an OlaDriver class with fields: driverId (String), name (String), vehicleType (String — "Auto", "Mini", "Prime"), rating (double), totalRides (int), isAvailable (boolean). Write a default constructor, parameterized constructor, and copy constructor.

I2. Add methods: acceptRide(String pickup, String drop) — sets isAvailable to false, prints ride details. completeRide(int fare, int driverRating) — increments totalRides, updates average rating, sets isAvailable to true. displayProfile() — prints all details.

I3. Add a static method findNearestDriver(OlaDriver[] drivers) that returns the first available driver. If none available, print "No drivers available." Demonstrate with an array of 5 OlaDriver objects.

Interview Questions (3)

IQ1. "What happens if you don't write any constructor in a Java class?"

Answer: Java provides a default no-argument constructor automatically. It initialises all fields to their default values (0 for int, 0.0 for double, null for objects, false for boolean). However, if you write even ONE constructor (of any type), Java stops providing the default constructor.

IQ2. "Can a constructor be private? When is it useful?"

Answer: Yes! A private constructor prevents other classes from creating objects using new. This is used in the Singleton design pattern — ensuring only ONE instance of a class exists (e.g., a database connection pool, a logger). The class provides a static method like getInstance() to return the single instance.

IQ3. "What is the difference between this and this()?"

Answer: this is a reference variable pointing to the current object — used to access fields and methods. this() is a constructor call — used to invoke another constructor of the same class (constructor chaining). this() must be the first statement in a constructor.

Section F

MCQ Assessment Bank — 30 Questions (Bloom's Mapped)

Remember / Identify (Q1–Q5)

Q1

A class in Java is:

  1. An instance of an object
  2. A blueprint/template for creating objects
  3. A method that returns an object
  4. A variable that stores data
Remember
✅ Answer: (B) — A class is a blueprint/template that defines the structure (fields) and behaviour (methods) of objects. Objects are instances of a class.
Q2

Which keyword is used to create an object in Java?

  1. class
  2. create
  3. new
  4. object
Remember
✅ Answer: (C) — The new keyword allocates memory for the object on the heap and calls the constructor.
Q3

A constructor in Java has:

  1. The same name as the class and a return type
  2. Any name and no return type
  3. The same name as the class and no return type
  4. A different name and void return type
Remember
✅ Answer: (C) — A constructor must have the same name as the class and NO return type (not even void).
Q4

How many types of constructors are there in Java?

  1. 1 (default only)
  2. 2 (default and parameterized)
  3. 3 (default, parameterized, and copy)
  4. 4 (default, parameterized, copy, and static)
Remember
✅ Answer: (C) — Java has 3 types: default (no args), parameterized (with args), and copy (takes object of same class). There is no "static constructor" in Java.
Q5

The this keyword in Java refers to:

  1. The parent class object
  2. The current class object
  3. A static variable
  4. The main method
Remember
✅ Answer: (B) — this is a reference to the current object — the object on which the method or constructor is being called.

Understand / Explain (Q6–Q10)

Q6

Why must this() be the first statement in a constructor?

  1. To improve performance
  2. Because Java needs to ensure the chained constructor runs before any other initialisation
  3. It's optional — it can be placed anywhere
  4. Because this is not initialised until the end of the constructor
Understand
✅ Answer: (B) — Java requires the chained constructor to complete first, ensuring the object is properly initialised before any other code runs in the current constructor.
Q7

What is the difference between an instance variable and a static variable?

  1. Instance variables are shared; static variables are per-object
  2. Instance variables belong to each object; static variables belong to the class and are shared
  3. There is no difference — they are the same
  4. Static variables can only be accessed inside constructors
Understand
✅ Answer: (B) — Instance variables get a separate copy per object. Static variables have ONE copy shared across all objects, belonging to the class itself.
Q8

Why can't a static method access instance variables directly?

  1. Static methods run before any object exists, so there's no instance to refer to
  2. Static methods don't have access to the JVM
  3. Instance variables are always private
  4. Static methods can only return void
Understand
✅ Answer: (A) — Static methods belong to the class, not to any specific object. Without an object, there are no instance variables to access. That's also why this is not available in static methods.
Q9

What happens when Java provides a default constructor?

  1. It initialises all fields to null only
  2. It initialises all fields to their default values (0, 0.0, null, false)
  3. It throws an exception
  4. It copies values from the parent class
Understand
✅ Answer: (B) — The Java-provided default constructor initialises numeric types to 0/0.0, boolean to false, and reference types to null.
Q10

In the DDA flat analogy, what does "creating multiple objects from one class" mean?

  1. Making multiple copies of the class file
  2. Building multiple flats (each with unique flat number) from the same blueprint
  3. Running multiple main methods
  4. Creating multiple constructors
Understand
✅ Answer: (B) — Just as DDA builds many flats from one blueprint (each with its own flat number, paint, furniture), you create many objects from one class — each with its own field values.

Apply / Predict Output (Q11–Q15)

Q11

What is the output?
class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } } new B();

  1. B A
  2. A B
  3. B
  4. Compilation Error
Apply
✅ Answer: (B) A B — When creating a subclass object, the parent constructor runs first (implicitly calls super()), then the child constructor.
Q12

What does Student s = new Student(); do in memory?

  1. Creates an object on the stack only
  2. Creates an object on the heap and a reference on the stack
  3. Creates an object on the heap only
  4. Creates a reference on the heap and an object on the stack
Apply
✅ Answer: (B) — The new keyword allocates the object on the heap. The reference variable s is stored on the stack and points to the heap object.
Q13

Given: void show(int a, double b) and void show(double a, int b), what happens with show(5, 5)?

  1. Calls first version
  2. Calls second version
  3. Compilation error — ambiguous
  4. Calls both versions
Apply
✅ Answer: (C) — Both 5s are int. Java can promote either one to double, but can't decide which — both methods are equally valid. This causes an "ambiguous method call" compilation error.
Q14

What is the output?
class Test { int x = 10; { x = 20; } Test() { x = 30; } } System.out.println(new Test().x);

  1. 10
  2. 20
  3. 30
  4. 0
Apply
✅ Answer: (C) 30 — Order: field initialisation (x=10) → instance block (x=20) → constructor (x=30). The last assignment wins.
Q15

What is the output?
class Counter { static int count = 0; Counter() { count++; } } new Counter(); new Counter(); new Counter(); System.out.println(Counter.count);

  1. 0
  2. 1
  3. 3
  4. Compilation error
Apply
✅ Answer: (C) 3 — Static variable count is shared. Each new Counter() increments it. After 3 objects: count = 3.

Apply / What Code (Q16–Q20)

Q16

To call one constructor from another in the same class, we use:

  1. super()
  2. this()
  3. new()
  4. constructor()
Apply
✅ Answer: (B) — this() calls another constructor of the same class. super() calls the parent class constructor.
Q17

Which access modifier makes a field accessible only within the same class?

  1. public
  2. protected
  3. default
  4. private
Apply
✅ Answer: (D) — private restricts access to the declaring class only. This is the foundation of encapsulation.
Q18

To enable method chaining, a setter method should:

  1. Return void
  2. Return the field value
  3. Return this
  4. Return a new object
Apply
✅ Answer: (C) — Returning this allows chaining: obj.setA(1).setB(2).setC(3);. Each setter returns the same object.
Q19

Which is the correct way to call a static method?

  1. obj.staticMethod() only
  2. ClassName.staticMethod() only
  3. Both A and B work, but B is preferred
  4. Neither — static methods cannot be called
Apply
✅ Answer: (C) — Both work, but calling via class name (Math.sqrt(25)) is the standard practice. Calling via an object reference works but is discouraged.
Q20

In method overloading, which of the following is NOT a valid way to overload?

  1. Different number of parameters
  2. Different types of parameters
  3. Different order of parameter types
  4. Different return type only
Apply
✅ Answer: (D) — Overloading requires different parameter lists. Return type alone cannot differentiate methods — the compiler looks at arguments to decide which method to call.

Analyze / Debug (Q21–Q25)

Q21

What's wrong with this code?
class Car { Car(String model) { } } Car c = new Car();

  1. Nothing — it compiles fine
  2. Error — no default constructor exists because a parameterized constructor was defined
  3. Error — Car class must be public
  4. Error — missing return type in constructor
Analyze
✅ Answer: (B) — Since a parameterized constructor is defined, Java no longer provides a default constructor. new Car() tries to call a no-arg constructor that doesn't exist.
Q22

Why does this fail?
static void greet() { System.out.println(this.name); }

  1. this is not available in static methods
  2. name is not declared
  3. Static methods cannot print output
  4. The method should return a String
Analyze
✅ Answer: (A) — this refers to the current object, but static methods don't belong to any object. Therefore, this is not available in static context.
Q23

Comparing constructors and methods — which statement is TRUE?

  1. Constructors can be inherited by subclasses
  2. Constructors are called explicitly using dot notation
  3. Constructors have no return type; methods must have one
  4. Constructors can be called multiple times on the same object
Analyze
✅ Answer: (C) — Constructors have no return type (not even void). Methods must declare a return type. Constructors are NOT inherited, are called via new, and run only once per object creation.
Q24

What's the problem?
class A { A() { this(5); } A(int x) { this(); } }

  1. No problem — it compiles fine
  2. Recursive constructor invocation — infinite loop at compile time
  3. this() can only be used once
  4. Constructor names must be different
Analyze
✅ Answer: (B) — A() calls A(int), which calls A(), creating an infinite recursion. Java detects this at compile time and throws an error.
Q25

What is the order of execution when an object is created?

  1. Constructor → Static block → Instance block
  2. Static block → Constructor → Instance block
  3. Static block → Instance block → Constructor
  4. Instance block → Static block → Constructor
Analyze
✅ Answer: (C) — Static block runs once (class loading) → Instance block runs before each constructor → Constructor runs last. This is a favourite interview question.

Evaluate / Create (Q26–Q30)

Q26

When designing a Singleton class (only one instance allowed), the constructor should be:

  1. public
  2. protected
  3. private
  4. default
Evaluate
✅ Answer: (C) private — A private constructor prevents external instantiation. The class provides a static getInstance() method to return the single instance.
Q27

For a utility class like MathHelper with only helper methods, the best design is:

  1. All instance methods, create objects to use
  2. All static methods, private constructor to prevent instantiation
  3. Mix of static and instance methods
  4. Abstract class with no methods
Evaluate
✅ Answer: (B) — Utility classes should have all static methods and a private constructor. This matches Java's own Math class design — you never write new Math().
Q28

In a banking application, account balance should be:

  1. public — so anyone can see it
  2. private — accessed only through deposit/withdraw methods
  3. static — shared across all accounts
  4. protected — so subclasses can modify it directly
Evaluate
✅ Answer: (B) — Balance must be private to prevent unauthorized modification. Controlled access via deposit() and withdraw() methods enforces business rules (e.g., can't withdraw more than balance).
Q29

You need a Student class where you can create a student with just a name, with name + roll, or with all details. Best approach?

  1. Create 3 separate classes
  2. Use constructor overloading with constructor chaining
  3. Use only a default constructor and set fields later
  4. Use method overloading instead
Create
✅ Answer: (B) — Constructor overloading with chaining (this()) is the cleanest approach. The simplest constructors chain to the most complete one, avoiding code duplication.
Q30

To implement Zomato's "Reorder" feature (create new order with same items as previous), the best OOP approach is:

  1. Use a static method that returns a new order
  2. Use a copy constructor that takes the previous order object
  3. Use method overloading on placeOrder()
  4. Store all orders in a static array
Create
✅ Answer: (B) — A copy constructor creates a new object with the same data as an existing one. It gets a new orderId and fresh status, but copies items, restaurant, and address from the previous order.
Section G

Short Answer Questions (8)

SA1. Define a class and an object with a real-world analogy.

Answer: A class is a blueprint/template that defines the structure and behaviour of entities. An object is a specific instance of that class with actual values. Analogy: A class is like a DDA flat blueprint (defines 2BHK layout). An object is an actual flat (Flat #301 in Dwarka — with specific furniture, paint, and resident). One blueprint → many flats. One class → many objects.

SA2. What are the 3 types of constructors? Give syntax for each.

Answer:

1. Default Constructor: public Student() { name = "Unknown"; } — no parameters, sets defaults.

2. Parameterized Constructor: public Student(String name, int roll) { this.name = name; this.rollNo = roll; } — takes values at creation time.

3. Copy Constructor: public Student(Student other) { this.name = other.name; this.rollNo = other.rollNo; } — creates a duplicate of an existing object.

SA3. Explain 5 uses of the this keyword with one-line code examples.

Answer:

1. Distinguish field from parameter: this.name = name;

2. Constructor chaining: this(10, 20); — must be first statement

3. Pass current object: course.addStudent(this);

4. Return current object: return this; — enables method chaining

5. Access outer class from inner: Outer.this.x;

SA4. Differentiate between instance methods and static methods.

AspectInstance MethodStatic Method
Belongs toObjectClass
Called viaobj.method()ClassName.method()
AccessInstance + static membersStatic members only
thisAvailableNot available
Exampleacc.deposit(5000)Math.sqrt(25)

SA5. What is constructor chaining? How does this() work?

Answer: Constructor chaining is calling one constructor from another within the same class using this(). It avoids duplicating initialisation code. this() must be the first statement in the constructor. The chain flows to the target constructor, which executes first, then control returns. Example: A() → this(10) → A(int x) → this(10,20) → A(int x, int y). The deepest constructor executes first.

SA6. What is method overloading? Can we overload by return type only? Why?

Answer: Method overloading means having multiple methods with the same name but different parameter lists (different number, type, or order). No, we CANNOT overload by return type alone — because the compiler uses the method signature (name + parameters) to decide which method to call. If only return types differ, the compiler can't determine which version to invoke from the call site.

SA7. Explain access modifiers: public, private, protected, default.

Answer: public — accessible everywhere. private — accessible only within the declaring class. protected — accessible within the same package and subclasses in other packages. default (no keyword) — accessible only within the same package. Best practice: make fields private, methods public (encapsulation).

SA8. What is the object lifecycle in Java?

Answer: 1. Creationnew allocates heap memory, constructor initialises fields. 2. Usage — methods are called, fields are accessed. 3. Unreachable — when no reference points to the object (set to null, out of scope, or reassigned). 4. Garbage Collection — JVM's GC automatically reclaims memory. finalize() (deprecated) may run before destruction. You cannot force GC — System.gc() is only a request.

Section H

Long Answer Questions (3)

LA1. Explain constructors in Java in detail — types, rules, overloading, chaining. Write a complete Employee class demonstrating all concepts. (15 marks)

Answer:

A constructor is a special method in Java that is automatically called when an object is created using the new keyword. It initialises the object's state.

Rules of Constructors:

  1. Must have the same name as the class
  2. Has no return type (not even void)
  3. Called only once — at object creation
  4. Cannot be abstract, static, final, or synchronized
  5. If no constructor is written, Java provides a default no-arg constructor
  6. If any constructor is written, Java does NOT provide the default constructor

Types: (1) Default — no parameters. (2) Parameterized — accepts arguments. (3) Copy — takes object of same class.

Overloading: Multiple constructors with different parameter lists. Java picks the right one based on arguments.

Chaining: Using this() to call another constructor; must be the first statement.

Java
public class Employee {
    String name;
    int empId;
    String department;
    double salary;
    static int totalEmployees = 0;

    // Default Constructor
    public Employee() {
        this("Unknown", 0, "General", 25000.0);
    }

    // 2-param Constructor
    public Employee(String name, int empId) {
        this(name, empId, "General", 25000.0);
    }

    // Full Parameterized Constructor (master)
    public Employee(String name, int empId, String department, double salary) {
        this.name = name;
        this.empId = empId;
        this.department = department;
        this.salary = salary;
        totalEmployees++;
    }

    // Copy Constructor
    public Employee(Employee other) {
        this(other.name, other.empId + 1000, other.department, other.salary);
    }

    void display() {
        System.out.println(name + " | " + empId + " | " + department + " | ₹" + salary);
    }

    static int getTotalEmployees() { return totalEmployees; }
}

LA2. What is the this keyword? Explain all 5 uses with code examples. Why is it important in constructor overloading? (10 marks)

Answer:

The this keyword is a reference to the current object. It is used to resolve ambiguity, enable chaining, and pass the current object.

Use 1 — Resolve field/parameter ambiguity: When constructor parameters have the same name as fields, this.name = name; distinguishes the field from the parameter.

Use 2 — Constructor chaining: this(args) calls another constructor in the same class. Must be the first statement. Reduces code duplication when multiple constructors share logic.

Use 3 — Pass current object: someMethod(this); passes the current object to another method or class.

Use 4 — Return current object: return this; enables method chaining (Builder pattern): obj.setA(1).setB(2).setC(3);

Use 5 — Inner class access: OuterClass.this.field accesses the outer class's field from within an inner class.

Importance in constructor overloading: this() enables constructors to delegate to each other, avoiding repetition of initialisation logic. The simplest constructor chains to more complete ones, ensuring consistent initialisation.

LA3. Compare class vs object, instance vs static, overloading vs overriding. Write a BankAccount class showing all concepts. (15 marks)

Answer:

Class vs Object: A class is a logical blueprint (no memory); an object is a physical instance in heap memory. Class is defined once; many objects can be created.

Instance vs Static: Instance members belong to each object (separate copies). Static members belong to the class (shared). Instance methods can use this; static methods cannot. Static is called via ClassName; instance via objectReference.

Overloading vs Overriding: Overloading = same method name, different parameters, same class (compile-time polymorphism). Overriding = same method name + same parameters, subclass redefines parent method (runtime polymorphism — covered in Unit 7).

Java
public class BankAccount {
    private String accNo;
    private double balance;
    private static int totalAccounts = 0;  // static — shared

    public BankAccount(String accNo, double balance) {
        this.accNo = accNo;       // this — instance
        this.balance = balance;
        totalAccounts++;           // static — incremented for every object
    }

    // Overloaded deposit — 2 versions
    public void deposit(double amount) { balance += amount; }
    public void deposit(double amount, String note) {
        deposit(amount);
        System.out.println("Note: " + note);
    }

    public static int getTotalAccounts() { return totalAccounts; }  // static method
    public double getBalance() { return balance; }                    // instance method
}
Section I

Lab Programs — Lab 3 & Lab 5

🔬 Lab 3: Creating Java Main Class

⏱️ 90 minutes📝 Write programs demonstrating class creation, object instantiation, and method calling

Program 3a: Basic Class with Fields and Methods

Aim: Create a Student class with fields and methods. Create objects and call methods.

Java
class Student {
    String name;
    int rollNo;
    double marks;
    String grade;

    void calculateGrade() {
        if (marks >= 90) grade = "A+";
        else if (marks >= 80) grade = "A";
        else if (marks >= 70) grade = "B";
        else if (marks >= 60) grade = "C";
        else grade = "F";
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll No: " + rollNo);
        System.out.println("Marks: " + marks);
        System.out.println("Grade: " + grade);
        System.out.println("---");
    }
}

public class Lab3a {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Aarav Patel";
        s1.rollNo = 101;
        s1.marks = 92.5;
        s1.calculateGrade();

        Student s2 = new Student();
        s2.name = "Meera Singh";
        s2.rollNo = 102;
        s2.marks = 76.0;
        s2.calculateGrade();

        s1.display();
        s2.display();
    }
}
Name: Aarav Patel Roll No: 101 Marks: 92.5 Grade: A+ --- Name: Meera Singh Roll No: 102 Marks: 76.0 Grade: B ---

Program 3b: Class with Multiple Methods and Object Interaction

Aim: Create a Rectangle class with methods for area, perimeter, and comparison.

Java
class Rectangle {
    double length;
    double width;

    double area() {
        return length * width;
    }

    double perimeter() {
        return 2 * (length + width);
    }

    boolean isSquare() {
        return length == width;
    }

    boolean isLargerThan(Rectangle other) {
        return this.area() > other.area();
    }

    void display() {
        System.out.println("Rectangle [" + length + " x " + width + "]");
        System.out.println("  Area: " + area() + ", Perimeter: " + perimeter());
        System.out.println("  Is Square? " + isSquare());
    }
}

public class Lab3b {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();
        r1.length = 10;
        r1.width = 5;

        Rectangle r2 = new Rectangle();
        r2.length = 7;
        r2.width = 7;

        r1.display();
        r2.display();

        System.out.println("r1 larger than r2? " + r1.isLargerThan(r2));
    }
}
Rectangle [10.0 x 5.0] Area: 50.0, Perimeter: 30.0 Is Square? false Rectangle [7.0 x 7.0] Area: 49.0, Perimeter: 28.0 Is Square? true r1 larger than r2? true

Program 3c: Class with Static and Instance Members

Aim: Demonstrate the difference between static and instance variables/methods.

Java
class BankAccount {
    String holderName;
    double balance;
    static int totalAccounts = 0;
    static double totalDeposits = 0;

    BankAccount(String name, double balance) {
        this.holderName = name;
        this.balance = balance;
        totalAccounts++;
        totalDeposits += balance;
    }

    void deposit(double amount) {
        balance += amount;
        totalDeposits += amount;
        System.out.println(holderName + ": Deposited ₹" + amount);
    }

    void displayAccount() {
        System.out.println(holderName + " — Balance: ₹" + balance);
    }

    static void displayBankStats() {
        System.out.println("Total Accounts: " + totalAccounts);
        System.out.println("Total Deposits: ₹" + totalDeposits);
    }
}

public class Lab3c {
    public static void main(String[] args) {
        BankAccount a1 = new BankAccount("Rahul", 50000);
        BankAccount a2 = new BankAccount("Priya", 75000);

        a1.deposit(10000);
        a2.deposit(25000);

        a1.displayAccount();
        a2.displayAccount();

        BankAccount.displayBankStats();
    }
}
Rahul: Deposited ₹10000.0 Priya: Deposited ₹25000.0 Rahul — Balance: ₹60000.0 Priya — Balance: ₹100000.0 Total Accounts: 2 Total Deposits: ₹160000.0

Lab 3 — Viva Questions

V1. What is the purpose of the main method?

The main method is the entry point of a Java program. JVM calls it first. It must be public static void main(String[] args). It's static so JVM can call it without creating an object.

V2. What is the difference between a class and an object?

A class is a template/blueprint (logical); an object is an instance of a class (physical, in memory). Class is defined once; multiple objects can be created from it.

V3. Can we have multiple classes in one Java file?

Yes, but only ONE class can be public, and the file must be named after that public class. Other classes in the same file must not be public.

V4. What are instance variables?

Variables declared inside a class but outside any method. Each object gets its own copy. They are initialised to default values (0, null, false) if not explicitly set.

V5. Why do we use this in constructors?

To distinguish between instance variables and parameters with the same name. this.name refers to the field; name refers to the parameter.

🔬 Lab 5: Describing Objects and Classes

⏱️ 120 minutes📝 Demonstrate constructors, constructor overloading, method overloading, and the this keyword

Program 5a: Constructor Types Demonstration

Aim: Demonstrate default, parameterized, and copy constructors in a Course class.

Java
class Course {
    String courseName;
    String instructor;
    int credits;
    double fee;

    // Default Constructor
    Course() {
        courseName = "Elective";
        instructor = "TBA";
        credits = 3;
        fee = 5000.0;
        System.out.println("Default constructor → " + courseName);
    }

    // Parameterized Constructor
    Course(String courseName, String instructor, int credits, double fee) {
        this.courseName = courseName;
        this.instructor = instructor;
        this.credits = credits;
        this.fee = fee;
        System.out.println("Parameterized constructor → " + courseName);
    }

    // Copy Constructor
    Course(Course other) {
        this.courseName = other.courseName;
        this.instructor = other.instructor;
        this.credits = other.credits;
        this.fee = other.fee;
        System.out.println("Copy constructor → copied " + other.courseName);
    }

    void display() {
        System.out.println(courseName + " | " + instructor +
                           " | Credits: " + credits + " | Fee: ₹" + fee);
    }
}

public class Lab5a {
    public static void main(String[] args) {
        Course c1 = new Course();
        Course c2 = new Course("Data Structures", "Prof. Sharma", 4, 12000.0);
        Course c3 = new Course(c2);

        System.out.println("\n--- All Courses ---");
        c1.display();
        c2.display();
        c3.display();
    }
}
Default constructor → Elective Parameterized constructor → Data Structures Copy constructor → copied Data Structures --- All Courses --- Elective | TBA | Credits: 3 | Fee: ₹5000.0 Data Structures | Prof. Sharma | Credits: 4 | Fee: ₹12000.0 Data Structures | Prof. Sharma | Credits: 4 | Fee: ₹12000.0

Program 5b: Constructor Overloading and Chaining

Aim: Demonstrate constructor overloading with chaining using this().

Java
class Laptop {
    String brand;
    String processor;
    int ram;
    double price;

    // Master constructor (all fields)
    Laptop(String brand, String processor, int ram, double price) {
        this.brand = brand;
        this.processor = processor;
        this.ram = ram;
        this.price = price;
        System.out.println("[Master] All fields set");
    }

    // 3-param — chains to master
    Laptop(String brand, String processor, int ram) {
        this(brand, processor, ram, 45000.0);
        System.out.println("[3-param] Default price ₹45000");
    }

    // 2-param — chains to 3-param
    Laptop(String brand, String processor) {
        this(brand, processor, 8);
        System.out.println("[2-param] Default RAM 8GB");
    }

    // Default — chains to 2-param
    Laptop() {
        this("HP", "i3");
        System.out.println("[Default] HP i3 8GB ₹45000");
    }

    void display() {
        System.out.println(brand + " | " + processor + " | " + ram + "GB | ₹" + price);
    }
}

public class Lab5b {
    public static void main(String[] args) {
        System.out.println("--- Creating default laptop ---");
        Laptop l1 = new Laptop();
        l1.display();

        System.out.println("\n--- Creating custom laptop ---");
        Laptop l2 = new Laptop("Dell", "i7", 16, 85000.0);
        l2.display();
    }
}
--- Creating default laptop --- [Master] All fields set [3-param] Default price ₹45000 [2-param] Default RAM 8GB [Default] HP i3 8GB ₹45000 HP | i3 | 8GB | ₹45000.0 --- Creating custom laptop --- [Master] All fields set Dell | i7 | 16GB | ₹85000.0

Program 5c: Method Overloading with Different Parameter Types

Aim: Demonstrate method overloading in a Printer class with different parameter combinations.

Java
class Printer {
    // Overloaded print() methods
    void print(String text) {
        System.out.println("String: " + text);
    }

    void print(int number) {
        System.out.println("Integer: " + number);
    }

    void print(double number) {
        System.out.println("Double: " + number);
    }

    void print(String text, int times) {
        for (int i = 0; i < times; i++) {
            System.out.print(text + " ");
        }
        System.out.println();
    }

    void print(String[] arr) {
        System.out.print("Array: ");
        for (String s : arr) {
            System.out.print(s + " ");
        }
        System.out.println();
    }
}

public class Lab5c {
    public static void main(String[] args) {
        Printer p = new Printer();
        p.print("Hello Java");
        p.print(42);
        p.print(3.14);
        p.print("OOP", 3);
        p.print(new String[]{"Java", "Python", "C++"});
    }
}
String: Hello Java Integer: 42 Double: 3.14 OOP OOP OOP Array: Java Python C++

Lab 5 — Viva Questions

V1. What is constructor overloading?

Having multiple constructors in the same class with different parameter lists. Java selects the appropriate constructor based on the arguments passed to new.

V2. Can a constructor return a value?

No. Constructors have no return type. If you add a return type (even void), it becomes a regular method, not a constructor.

V3. What is the difference between method overloading and constructor overloading?

Both involve multiple versions with different parameters. Method overloading applies to any method. Constructor overloading applies only to constructors (same name as class, no return type).

V4. What happens if this() is not the first statement?

Compilation error. Java requires this() to be the first statement to ensure proper object initialisation order.

V5. Can we have both this() and super() in the same constructor?

No. Both must be the first statement, so only one can be used. If you use this(), it chains within the class. If you use super(), it calls the parent constructor.

Section J

Industry Spotlight — A Day in the Life

👩‍💻 Kavitha Rajan, 28 — Senior Java Developer at Flipkart, Bangalore

Background: B.Tech in Computer Science from Anna University, Chennai. Started coding in Java during 2nd year. Built a Library Management System as her mini-project using OOP. Interned at a Chennai startup, then got placed at Flipkart through off-campus drive.

A Typical Day:

9:00 AM — Morning standup with the Product Catalog team. Review yesterday's sprint tasks. Discuss a bug in the Product class constructor that's causing null pointer exceptions in production.

10:00 AM — Code review of a junior developer's pull request. The new Offer class has poor encapsulation — fields are public. Kavitha suggests making them private with getters/setters and adding validation in the constructor.

11:30 AM — Writing unit tests for the PaymentProcessor class. Testing edge cases: what if the constructor receives null values? What if processPayment() is called twice on the same order?

1:00 PM — Lunch at Flipkart's EcoSpace cafeteria. Chat about the new Builder pattern implementation for the ProductListing class — 15 optional fields make constructor overloading unwieldy.

2:30 PM — Implementing a new SubscriptionPlan class for Flipkart Plus. Uses constructor chaining: default plan → monthly → annual. Method chaining for configuration: plan.setDuration(12).setDiscount(15).activate();

4:30 PM — Mentoring a junior developer on OOP best practices: "Don't put all logic in main(). Break it into meaningful classes. Each class = one responsibility."

5:30 PM — Learning Kotlin (used in Flipkart's Android app). Many OOP concepts transfer directly from Java.

DetailInfo
Tools Used DailyIntelliJ IDEA, Git, Spring Boot, JUnit, Maven, Jenkins, JIRA
Entry Salary (2024)₹4–8 LPA + benefits
Mid-Level (3–5 yrs)₹10–18 LPA
Senior (7+ yrs)₹20–40 LPA
Companies HiringFlipkart, Amazon, Ola, Swiggy, Paytm, TCS, Infosys, Wipro, HCL, Zoho, Razorpay, PhonePe
Section K

Earn With It — OOP Desktop Apps ₹8K–₹25K/month

💰 Your Earning Path After This Chapter

Portfolio Pieces:

• Library Management System — CRUD operations with proper OOP classes

• Student Record System — constructors, encapsulation, method overloading

• Billing/Invoice System — multiple classes interacting (Product, Invoice, Customer)

Gig Ideas:

• Desktop apps for local businesses (billing, inventory) — ₹5,000–₹15,000

• Android apps for small shops (order management) — ₹8,000–₹25,000

• Custom CRUD applications for coaching centres — ₹3,000–₹10,000

• API backend development (Spring Boot) — ₹10,000–₹25,000

PlatformBest ForTypical Rate
InternshalaStudent projects & internships₹3,000–₹10,000/project
FiverrGlobal clients, Java projects$20–$100/gig (₹1,600–₹8,000)
UpworkLonger Java/Spring Boot projects$20–$50/hour
LinkedInDirect outreach, networking₹5,000–₹15,000/project
Local BusinessesBilling, inventory systems₹5,000–₹20,000/project

⏱️ Time to First Earning: 3–4 weeks (if you complete Lab 3, Lab 5, and build 1 portfolio project)

Your OOP knowledge + Spring Boot = full-stack Java developer. Start with desktop apps (Swing/JavaFX), then learn Spring Boot for web APIs. This path takes you from ₹8K freelance gigs to ₹6–12 LPA full-time jobs. Indian IT companies hire 500,000+ Java developers annually.
Section L

Chapter Summary

🎯 Key Takeaways — Unit 6: OOP

Class = Blueprint, Object = Instance — DDA flat analogy. Class defines structure; object is the real thing in memory.

3 Constructor Types: Default (no args), Parameterized (with args), Copy (clone an object).

Constructor Overloading: Multiple constructors, different parameters. Java picks the right one.

Constructor Chaining: this() calls another constructor — must be first statement.

5 Uses of this: (1) field vs param (2) constructor call (3) pass object (4) return object (5) inner class reference.

Method Overloading: Same name, different parameters. Return type alone doesn't count.

Static vs Instance: Static belongs to class (shared), Instance belongs to object (separate copies).

Access Modifiers: public → everywhere, private → same class, protected → package + subclass, default → package only.

Object Lifecycle: Creation (new) → Usage (methods) → Unreachable → Garbage Collection.

Initializer Blocks: Static block (once) → Instance block (every time) → Constructor.

💬 CODE TWEET

class ZomatoOrder { String orderId; void placeOrder(){} }

// Every app you use is just classes & objects talking to each other.

// Master OOP = Master Java. 🚀 #JavaOOP #EduArtha

Section M

Earning & Learning Checkpoint

ConceptTool / MethodPortfolio OutputEarning Ready?
Class & ObjectJava class definition + newStudent, Rectangle classes✅ Yes — foundation for all projects
ConstructorsDefault, Parameterized, CopyStudentRecord, Course classes✅ Yes — critical interview topic
Constructor Chainingthis()Employee, Laptop chaining demo✅ Yes — asked in 80% interviews
this Keyword5 uses in codePizza builder with method chaining✅ Yes — shows advanced understanding
Method OverloadingSame name, different paramsCalculator, Printer overloading✅ Yes — used in every Java project
Static vs Instancestatic keywordCounter, BankAccount stats✅ Yes — utility classes & design patterns
Lab 3: Main ClassIntelliJ / VS Code3 programs with full output✅ Yes — can build basic Java apps
Lab 5: Objects & ClassesIntelliJ / VS Code3 programs: constructors + overloading✅ Yes — ready for freelance projects
Minimum Viable Earning Setup after this chapter: A GitHub repo with 3 OOP Java projects (Library System, Student Records, Billing App) + an Internshala/Fiverr profile offering "Java Desktop Application Development" = you can earn ₹8,000–₹25,000/month from coding gigs while still in college.

✅ Unit 6 complete. MCQs: 30. Labs 3, 5 covered. Ready for Unit 7 — Inheritance & Polymorphism!

[QR: Link to EduArtha video tutorial — Java OOP: Classes, Objects & Constructors]