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)
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.
Learning Outcomes — Bloom's Taxonomy Mapped
| Bloom's Level | Learning Outcome |
|---|---|
| 🔵 Remember | Define class, object, constructor, method, and the this keyword with correct Java syntax |
| 🔵 Remember | List the 5 uses of the this keyword and 3 types of constructors in Java |
| 🔵 Understand | Explain the difference between class and object using the DDA flat blueprint analogy |
| 🔵 Understand | Describe how constructor chaining works using this() and super() |
| 🟢 Apply | Write a BankAccount class with parameterized constructor, deposit(), withdraw(), and getBalance() |
| 🟢 Apply | Implement constructor overloading with default, parameterized, and copy constructors |
| 🟢 Analyze | Differentiate between instance methods and static methods with real code examples |
| 🟢 Analyze | Compare method overloading vs method overriding (preview for Unit 7) |
| 🟠 Evaluate | Debug constructor chaining errors and predict output of complex this() calls |
| 🟠 Evaluate | Assess when to use static methods vs instance methods in application design |
| 🟠 Create | Design a complete ZomatoOrder class with multiple constructors and business logic methods |
| 🟠 Create | Build a StudentRecord management system with proper OOP encapsulation |
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
| Aspect | Class | Object |
|---|---|---|
| Definition | A blueprint/template for creating objects | An instance of a class — a real entity in memory |
| Memory | No memory allocated when class is defined | Memory allocated when object is created with new |
| Existence | Logical — exists in code only | Physical — exists in heap memory at runtime |
| Created | Using the class keyword | Using the new keyword |
| Analogy | DDA flat blueprint | Actual flat in Dwarka (Flat #301, #302…) |
| Count | Defined once | Many 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(); } }
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()); } }
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
| Type | Description | When to Use |
|---|---|---|
| Default | No parameters. Sets default values. | When you want a "blank" object with sensible defaults |
| Parameterized | Takes parameters to initialise fields. | When you know all values at creation time |
| Copy | Takes 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(); } }
new StudentRecord() will give a compilation error! You must explicitly write the default constructor too if you need both.
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(); } }
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(); } }
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:
| Aspect | Instance Method | Static Method |
|---|---|---|
| Belongs to | Object (instance) | Class itself |
| Called via | objectName.method() | ClassName.method() |
| Access | Can access instance + static variables | Can access static variables ONLY |
this keyword | ✅ Available | ❌ Not available |
| Example | acc.deposit(5000) | Math.sqrt(25) |
| Memory | Needs object to be created first | Available 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(); } }
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")); } }
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(); } }
9. Initializer Blocks
Java has two types of initializer blocks that run before or during object creation:
| Type | Syntax | When It Runs | Use Case |
|---|---|---|---|
| Static Block | static { ... } | Once — when class is first loaded | Database 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(); } }
10. Access Modifiers in OOP
| Modifier | Same Class | Same Package | Subclass (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! }
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
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()); } }
Learn by Doing — 3-Tier Lab Structure
🟢 Tier 1 — GUIDED TASK: Build a Basic ZomatoOrder Class
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(); } }
🎉 Congratulations! You've built your first OOP class with constructors and methods!
🟡 Tier 2 — SEMI-GUIDED: Extend with Constructor Overloading & Static Methods
Your Mission:
Extend the Tier 1 ZomatoOrder class with these features:
- Copy Constructor: Add a constructor that takes another
ZomatoOrderobject and creates a "Reorder" (new orderId, same items) - Overloaded
placeOrder(): Add a version that acceptsString deliveryInstructions - Static field
orderCount: Track total orders created across all objects - Static method
getOrderCount(): Return total order count - Method chaining: Make
setCustomerName(),setRestaurant()returnthis
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
The Brief:
Design a complete Restaurant Management System with these classes:
MenuItem— name, price, category (veg/non-veg), isAvailable. Overloaded constructors.Restaurant— name, location, rating, menu (array of MenuItem). Methods: addItem(), removeItem(), displayMenu().ZomatoOrder— extends Tier 2 class. Adds delivery time estimation.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
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.
MCQ Assessment Bank — 30 Questions (Bloom's Mapped)
Remember / Identify (Q1–Q5)
A class in Java is:
- An instance of an object
- A blueprint/template for creating objects
- A method that returns an object
- A variable that stores data
Which keyword is used to create an object in Java?
- class
- create
- new
- object
new keyword allocates memory for the object on the heap and calls the constructor.A constructor in Java has:
- The same name as the class and a return type
- Any name and no return type
- The same name as the class and no return type
- A different name and void return type
How many types of constructors are there in Java?
- 1 (default only)
- 2 (default and parameterized)
- 3 (default, parameterized, and copy)
- 4 (default, parameterized, copy, and static)
The this keyword in Java refers to:
- The parent class object
- The current class object
- A static variable
- The main method
this is a reference to the current object — the object on which the method or constructor is being called.Understand / Explain (Q6–Q10)
Why must this() be the first statement in a constructor?
- To improve performance
- Because Java needs to ensure the chained constructor runs before any other initialisation
- It's optional — it can be placed anywhere
- Because
thisis not initialised until the end of the constructor
What is the difference between an instance variable and a static variable?
- Instance variables are shared; static variables are per-object
- Instance variables belong to each object; static variables belong to the class and are shared
- There is no difference — they are the same
- Static variables can only be accessed inside constructors
Why can't a static method access instance variables directly?
- Static methods run before any object exists, so there's no instance to refer to
- Static methods don't have access to the JVM
- Instance variables are always private
- Static methods can only return void
this is not available in static methods.What happens when Java provides a default constructor?
- It initialises all fields to null only
- It initialises all fields to their default values (0, 0.0, null, false)
- It throws an exception
- It copies values from the parent class
In the DDA flat analogy, what does "creating multiple objects from one class" mean?
- Making multiple copies of the class file
- Building multiple flats (each with unique flat number) from the same blueprint
- Running multiple main methods
- Creating multiple constructors
Apply / Predict Output (Q11–Q15)
What is the output?class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } } new B();
- B A
- A B
- B
- Compilation Error
What does Student s = new Student(); do in memory?
- Creates an object on the stack only
- Creates an object on the heap and a reference on the stack
- Creates an object on the heap only
- Creates a reference on the heap and an object on the stack
new keyword allocates the object on the heap. The reference variable s is stored on the stack and points to the heap object.Given: void show(int a, double b) and void show(double a, int b), what happens with show(5, 5)?
- Calls first version
- Calls second version
- Compilation error — ambiguous
- Calls both versions
What is the output?class Test { int x = 10; { x = 20; } Test() { x = 30; } } System.out.println(new Test().x);
- 10
- 20
- 30
- 0
What is the output?class Counter { static int count = 0; Counter() { count++; } } new Counter(); new Counter(); new Counter(); System.out.println(Counter.count);
- 0
- 1
- 3
- Compilation error
count is shared. Each new Counter() increments it. After 3 objects: count = 3.Apply / What Code (Q16–Q20)
To call one constructor from another in the same class, we use:
super()this()new()constructor()
this() calls another constructor of the same class. super() calls the parent class constructor.Which access modifier makes a field accessible only within the same class?
- public
- protected
- default
- private
private restricts access to the declaring class only. This is the foundation of encapsulation.To enable method chaining, a setter method should:
- Return void
- Return the field value
- Return
this - Return a new object
this allows chaining: obj.setA(1).setB(2).setC(3);. Each setter returns the same object.Which is the correct way to call a static method?
obj.staticMethod()onlyClassName.staticMethod()only- Both A and B work, but B is preferred
- Neither — static methods cannot be called
Math.sqrt(25)) is the standard practice. Calling via an object reference works but is discouraged.In method overloading, which of the following is NOT a valid way to overload?
- Different number of parameters
- Different types of parameters
- Different order of parameter types
- Different return type only
Analyze / Debug (Q21–Q25)
What's wrong with this code?class Car { Car(String model) { } } Car c = new Car();
- Nothing — it compiles fine
- Error — no default constructor exists because a parameterized constructor was defined
- Error — Car class must be public
- Error — missing return type in constructor
new Car() tries to call a no-arg constructor that doesn't exist.Why does this fail?static void greet() { System.out.println(this.name); }
thisis not available in static methodsnameis not declared- Static methods cannot print output
- The method should return a String
this refers to the current object, but static methods don't belong to any object. Therefore, this is not available in static context.Comparing constructors and methods — which statement is TRUE?
- Constructors can be inherited by subclasses
- Constructors are called explicitly using dot notation
- Constructors have no return type; methods must have one
- Constructors can be called multiple times on the same object
new, and run only once per object creation.What's the problem?class A { A() { this(5); } A(int x) { this(); } }
- No problem — it compiles fine
- Recursive constructor invocation — infinite loop at compile time
- this() can only be used once
- Constructor names must be different
A() calls A(int), which calls A(), creating an infinite recursion. Java detects this at compile time and throws an error.What is the order of execution when an object is created?
- Constructor → Static block → Instance block
- Static block → Constructor → Instance block
- Static block → Instance block → Constructor
- Instance block → Static block → Constructor
Evaluate / Create (Q26–Q30)
When designing a Singleton class (only one instance allowed), the constructor should be:
- public
- protected
- private
- default
getInstance() method to return the single instance.For a utility class like MathHelper with only helper methods, the best design is:
- All instance methods, create objects to use
- All static methods, private constructor to prevent instantiation
- Mix of static and instance methods
- Abstract class with no methods
Math class design — you never write new Math().In a banking application, account balance should be:
- public — so anyone can see it
- private — accessed only through deposit/withdraw methods
- static — shared across all accounts
- protected — so subclasses can modify it directly
deposit() and withdraw() methods enforces business rules (e.g., can't withdraw more than balance).You need a Student class where you can create a student with just a name, with name + roll, or with all details. Best approach?
- Create 3 separate classes
- Use constructor overloading with constructor chaining
- Use only a default constructor and set fields later
- Use method overloading instead
this()) is the cleanest approach. The simplest constructors chain to the most complete one, avoiding code duplication.To implement Zomato's "Reorder" feature (create new order with same items as previous), the best OOP approach is:
- Use a static method that returns a new order
- Use a copy constructor that takes the previous order object
- Use method overloading on placeOrder()
- Store all orders in a static array
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.
| Aspect | Instance Method | Static Method |
|---|---|---|
| Belongs to | Object | Class |
| Called via | obj.method() | ClassName.method() |
| Access | Instance + static members | Static members only |
this | Available | Not available |
| Example | acc.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. Creation — new 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.
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:
- Must have the same name as the class
- Has no return type (not even void)
- Called only once — at object creation
- Cannot be abstract, static, final, or synchronized
- If no constructor is written, Java provides a default no-arg constructor
- 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 }
Lab Programs — Lab 3 & Lab 5
🔬 Lab 3: Creating Java Main Class
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(); } }
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)); } }
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(); } }
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
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(); } }
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(); } }
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++"}); } }
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.
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.
| Detail | Info |
|---|---|
| Tools Used Daily | IntelliJ 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 Hiring | Flipkart, Amazon, Ola, Swiggy, Paytm, TCS, Infosys, Wipro, HCL, Zoho, Razorpay, PhonePe |
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
| Platform | Best For | Typical Rate |
|---|---|---|
| Internshala | Student projects & internships | ₹3,000–₹10,000/project |
| Fiverr | Global clients, Java projects | $20–$100/gig (₹1,600–₹8,000) |
| Upwork | Longer Java/Spring Boot projects | $20–$50/hour |
| Direct outreach, networking | ₹5,000–₹15,000/project | |
| Local Businesses | Billing, 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)
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
Earning & Learning Checkpoint
| Concept | Tool / Method | Portfolio Output | Earning Ready? |
|---|---|---|---|
| Class & Object | Java class definition + new | Student, Rectangle classes | ✅ Yes — foundation for all projects |
| Constructors | Default, Parameterized, Copy | StudentRecord, Course classes | ✅ Yes — critical interview topic |
| Constructor Chaining | this() | Employee, Laptop chaining demo | ✅ Yes — asked in 80% interviews |
| this Keyword | 5 uses in code | Pizza builder with method chaining | ✅ Yes — shows advanced understanding |
| Method Overloading | Same name, different params | Calculator, Printer overloading | ✅ Yes — used in every Java project |
| Static vs Instance | static keyword | Counter, BankAccount stats | ✅ Yes — utility classes & design patterns |
| Lab 3: Main Class | IntelliJ / VS Code | 3 programs with full output | ✅ Yes — can build basic Java apps |
| Lab 5: Objects & Classes | IntelliJ / VS Code | 3 programs: constructors + overloading | ✅ Yes — ready for freelance projects |
✅ 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]