In Java, classes and objects form the structural foundation of all application logic. A class acts as the blueprint, and an object is the physical living instance produced from that blueprint.
Figure 6: Memory Trace: Class Template in Metaspace, Reference Variable on Call Stack, and Object Instances in Heap.
A class definition groups fields (state) and methods (behavior):
public class Car {
// 1. State / Attributes (Instance Variables)
String brand;
String color;
int currentSpeed;
// 2. Behavior / Actions (Methods)
public void accelerate(int speedIncrease) {
currentSpeed += speedIncrease;
System.out.println(brand + " accelerated to: " + currentSpeed + " km/h");
}
public void applyBrakes() {
currentSpeed = 0;
System.out.println(brand + " has come to a complete halt.");
}
}
new KeywordTo bring a class to life, you instantiate an object using the new operator. Each object possesses its own independent copy of instance variables:
public class CarShowroom {
public static void main(String[] args) {
// Step 1: Create first Car object
Car car1 = new Car();
car1.brand = "Toyota Fortuner";
car1.color = "Pearl White";
car1.currentSpeed = 60;
// Step 2: Create second Car object
Car car2 = new Car();
car2.brand = "Tesla Model 3";
car2.color = "Midnight Silver";
car2.currentSpeed = 85;
// Step 3: Invoke methods via dot operator (.)
car1.accelerate(20); // Toyota accelerated to 80 km/h
car2.applyBrakes(); // Tesla has come to a complete halt
}
}
Car car1 is declared inside main(), the JVM allocates 4 or 8 bytes on the Call Stack for the local variable car1. Initially, it holds a memory address pointer (e.g. 0x4A12).new Car() allocates contiguous memory on the Heap for the Car instance. The fields (brand, color, currentSpeed) reside inside this Heap block.Exam Question: "What is the output of the following code?"
Car c1 = new Car();
c1.brand = "Ford";
Car c2 = c1;
c2.brand = "BMW";
System.out.println(c1.brand);
Output: BMW
Explanation: In Java, assigning an object variable (Car c2 = c1;) does NOT copy the object! It copies the reference pointer. Both c1 and c2 point to the exact same memory address on the Heap. Modifying c2.brand directly mutates the shared object.
Now let us explore constructors, default constructors, and constructor chaining. Proceed to: Java Constructors & Chaining →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Initializing object state.
Referencing the current object.
Object lifecycle and GC.
Protecting object fields.