M O D U L E

Module 5: Object-Oriented Programming — Classes & Objects

Class blueprints, heap object instantiation, constructors, the this keyword, method overloading, and static vs instance state.

5.1 Classes and Objects

A Class is a blueprint or template that defines what data an object will hold (its fields or attributes) and what actions it can perform (its methods). A class definition occupies memory in the JVM's Metaspace for its bytecode, but holds no data instances.

An Object is a concrete, living instance instantiated from a class template using the new keyword. When an object is created, the JVM allocates memory for it on the Heap and automatically executes a constructor to initialize its instance variables.

class Car {
    String color; // instance field
    int speed;

    void drive() {
        System.out.println(color + " car driving at " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car();
        c1.color = "Red";
        c1.speed = 100;

        Car c2 = new Car();
        c2.color = "Blue";
        c2.speed = 120; // c1 and c2 are completely independent instances on the heap!
    }
}
class Car { String color; int speed; void drive(){...} } object 1: c1 = new Car() color = "Red", speed = 100 object 2: c2 = new Car() color = "Blue", speed = 120
Figure 5.1 — A class is the blueprint; each object created with 'new' is a separate, independent instance on the heap.

💡 Placement & Interview Deep-Dive

  • Do all objects of the same class duplicate method code? NO! Method bytecode is shared in the Metaspace and executed collectively by all instances. Only instance variables get their own distinct memory copy per object on the heap.
  • What are the 3 steps in Java Object Creation?
    1. Declaration: Car c; associates a reference variable on the stack with the Car type.
    2. Instantiation: The new operator allocates heap memory for the object.
    3. Initialization: The constructor initializes fields and establishes starting state.

5.2 Constructors and the 'this' Keyword

A Constructor is a special member method that shares the exact same name as the class and has no return type — not even void. It is called automatically and exactly once whenever an object is instantiated with new.

The Role of the this Keyword

The this keyword is an implicit reference variable that points to the current executing object instance. Its two most essential uses are:

  • Resolving Naming Shadowing: When a constructor parameter has the exact same identifier as an instance variable, this.name refers to the instance field on the heap, while name refers to the local parameter on the stack:
    class Student {
        String name;
        int roll;
    
        Student(String name, int roll) {
            this.name = name; // this.name = instance field, name = parameter
            this.roll = roll;
        }
    }
  • Constructor Chaining via this(): Calling another constructor in the same class. Crucial rule: The call to this(...) MUST be the first statement in the constructor body.

💡 Placement & Interview Deep-Dive

  • Can a constructor be marked final, static, or abstract? NO!
    • It cannot be final because constructors are never inherited and cannot be overridden.
    • It cannot be static because constructors operate on object instance creation.
    • It cannot be abstract because constructors must contain code to initialize an object.
  • Can a constructor be private? YES! Private constructors are fundamental to the Singleton Design Pattern (ensuring only one instance of a class exists) and Utility classes (like java.lang.Math) to prevent instantiation.
  • When is the default constructor created? The compiler automatically inserts a default no-arg constructor ONLY if the programmer defines NO constructors at all. Once you write any parameterized constructor, the default constructor is removed.

5.3 Methods and Method Overloading

Methods define the reusable operations and behavior that an object can perform. Java supports Method Overloading (also called Compile-Time Polymorphism): defining multiple methods in the same class with the exact same name but different parameter lists.

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

The Method Signature Rule

In Java, a method's signature consists exclusively of: Method Name + Parameter Type List.

Critical Overloading Rule:

Return type is NOT part of the method signature! You CANNOT overload a method by changing only the return type. Attempting to define int calculate() and double calculate() in the same class causes a compile-time error.

💡 Placement & Interview Deep-Dive: Method Resolution Hierarchy

When an overloaded method is called, the compiler resolves the target method using this strict priority order:

  1. Exact Type Match: add(int, int)
  2. Widening Primitive: int widens to long, then float, then double
  3. Autoboxing / Unboxing: int autoboxes to Integer
  4. Varargs: add(int... args) has the lowest matching priority.

5.4 Static vs Instance Members

Understanding the distinction between Static and Instance members is crucial for designing clean object architectures and mastering Java memory management:

  • Instance Members: Belong to each individual object. Every object created with new receives its own separate memory copy on the heap. Instance methods operate within the context of this.
  • Static Members: Marked with the static keyword and belong to the Class blueprint itself. Loaded once into the Metaspace when the class is loaded by the ClassLoader, and shared across all instances:
    class Student {
        String name;            // Instance variable: each student has their own name
        static String college = "MIT"; // Static variable: shared across all 1,000 students
    }
KEY TERM: Static vs. Instance

Think of instance members as belonging to each individual object (each Car has its own color), while static members belong to the blueprint itself, shared by every object of that class (like a running count of how many Cars have ever been made).

💡 Placement & Interview Deep-Dive

  • Can a static method access an instance variable directly? NO! Static methods execute without an object reference (there is no this pointer). Accessing an instance variable directly causes: Cannot make a static reference to the non-static field.
  • Can an instance method access static variables? YES! An instance method can access both instance members and class-level static members freely.
  • What is a Static Initialization Block? A block prefixed with static { ... } that executes once when the class is loaded into memory by the ClassLoader, prior to any constructors or object creation. Commonly used for loading native libraries or complex static configuration.
MODULE COMPREHENSIVE QUIZ

Module 5 Final Quiz

Test your understanding across all 4 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 5 Final Quiz →
Yukti Mascot