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!
}
}
💡 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?
- Declaration:
Car c;associates a reference variable on the stack with theCartype. - Instantiation: The
newoperator allocates heap memory for the object. - Initialization: The constructor initializes fields and establishes starting state.
- Declaration:
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.namerefers to the instance field on the heap, whilenamerefers 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 tothis(...)MUST be the first statement in the constructor body.
💡 Placement & Interview Deep-Dive
- Can a constructor be marked
final,static, orabstract? NO!- It cannot be
finalbecause constructors are never inherited and cannot be overridden. - It cannot be
staticbecause constructors operate on object instance creation. - It cannot be
abstractbecause constructors must contain code to initialize an object.
- It cannot be
- 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 (likejava.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.
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:
- Exact Type Match:
add(int, int) - Widening Primitive:
intwidens tolong, thenfloat, thendouble - Autoboxing / Unboxing:
intautoboxes toInteger - 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
newreceives its own separate memory copy on the heap. Instance methods operate within the context ofthis. - Static Members: Marked with the
statickeyword 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 }
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
thispointer). 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.