Java Class & Object Fundamentals: Blueprint vs Instance
Class ante enti? Β· Object ante enti? Β· Blueprint vs Instance Analogy Β· Fields (Instance Variables) Β· Methods Inside Classes Β· Creating Objects with new Β· Dot Operator Β· Memory Model: Stack Reference + Heap Object Β· Multiple Objects from One Class
Comprehensive masterclass on Java Object-Oriented Programming foundations: understanding the critical distinction between a class (blueprint/template) and an object (living instance in memory), defining fields and methods inside classes, allocating objects on the Heap with the new keyword, and navigating members using the dot operator.
1. Class Ante Enti? (What is a Class in Java?)
A Class is a blueprint, template, or architectural plan that describes two things:
1. Fields (State): What data/attributes an object should hold.
2. Methods (Behavior): What actions/operations the object can perform.
Real-World Analogy β Car Blueprint:
- The architectural blueprint of a car says: "Every car has a color, engine size, and fuel type. Every car can startEngine(), accelerate(), and brake()."
- But the blueprint itself is NOT a physical carβyou cannot sit in or drive a blueprint!
- It is only when a manufacturer builds (instantiates) a car from that blueprint that a real, usable car (object) comes into existence.
// 1. CLASS = Blueprint (Defines structure and behavior)
class Car {
String color; // Field (State)
int speed; // Field (State)
void accelerate() { // Method (Behavior)
speed += 10;
}
}
// 2. OBJECT = A real car built from the blueprint (Instantiation)
Car myCar = new Car(); // myCar is now a usable instance
2. Object Ante Enti? (What is an Object in Java?)
An Object is a concrete, usable instance of a class that exists in the JVM Heap memory at runtime.
Each object has:
1. Its own identity: A unique 64-bit memory address in the Heap.
2. Its own state: Independent values for every field defined in the class.
3. Shared behavior: Methods defined in the class are shared (not duplicated) via the JVM Method Area.
CLASS (Method Area - Template) HEAP MEMORY (Runtime Objects)
+----------------------------+ +----------------+ +----------------+
| class Student { | | Object #1 | | Object #2 |
| String name; | | name = "Ravi" | | name = "Priya" |
| int age; | | age = 20 | | age = 22 |
| void display() { ... } | | Addr: 0x5A00 | | Addr: 0x6B00 |
| } | +----------------+ +----------------+
+----------------------------+3. Fields (Instance Variables) Explained
Fields (also called Instance Variables) are variables declared directly inside a class body but OUTSIDE any method:
class Student {
String name; // Instance field: EACH object gets its own copy
int age; // Instance field
double gpa; // Instance field
}Key Rules:
- Fields are allocated on the Heap as part of the object (not the Stack).
- Every object created from the class gets its own independent copy of each field.
- Fields are auto-initialized to default values (0, false, null) if not explicitly initialized in a constructor.
4. Creating Objects with new & The Dot Operator
The new keyword triggers 3 JVM operations:
1. Allocates memory in the Heap for the new object.
2. Initializes all fields to their default values (0 / false / null).
3. Invokes the constructor to set up the object's initial state.
The dot operator (.) navigates from a reference variable to an object's fields or methods:
Student s = new Student(); // s is a Stack reference pointing to a Heap object
s.name = "Ravi"; // Sets name field on the Heap object
s.age = 20; // Sets age field on the Heap object
s.displayDetails(); // Invokes displayDetails() method5. JVM Memory Model: Stack Reference + Heap Object
STACK MEMORY HEAP MEMORY
+-------------------+ +----------------------------+
| s1 = 0x4A00 | ------> | name: "Ravi" |
+-------------------+ | age : 20 |
| s2 = 0x7C00 | ------> +----------------------------+
+-------------------+ | name: "Priya" |
| age : 22 |
+----------------------------+The Null Pointer Hazard:
If you declare a reference but don't create an object, the reference variable contains null. Attempting to use the dot operator on a null reference throws NullPointerException:
Student ghost = null;
ghost.displayDetails(); // throws java.lang.NullPointerException!Beginner Example & Code Anatomy
class Student {
// Fields (Instance Variables)
String name;
int age;
// Method inside class (User requested core snippet)
void displayDetails() {
System.out.println(name + " - " + age);
}
}
public class Main {
public static void main(String[] args) {
System.out.println("=== 1. User Requested Primary Snippet ===");
Student student = new Student("Ravi", 20); // Note: This requires constructor
student.displayDetails(); // Will be extended in next chapter
System.out.println("
=== 2. Dot Operator: Setting Fields Directly ===");
Student s1 = new Student();
s1.name = "Priya Sharma";
s1.age = 22;
s1.displayDetails();
System.out.println("
=== 3. Multiple Independent Objects from One Class ===");
Student s2 = new Student();
s2.name = "Kiran Kumar";
s2.age = 21;
Student s3 = new Student();
s3.name = "Ananya Reddy";
s3.age = 23;
// Each object has its own state!
System.out.println("Object s1: "); s1.displayDetails();
System.out.println("Object s2: "); s2.displayDetails();
System.out.println("Object s3: "); s3.displayDetails();
System.out.println("
=== 4. Checking Object Identity ===");
System.out.println("s1 == s2 (same object?) : " + (s1 == s2));
Student s4 = s1; // s4 and s1 point to the SAME heap object!
System.out.println("s4 == s1 (same object?) : " + (s4 == s1));
s4.name = "MODIFIED via s4";
System.out.println("s1.name after s4 change : " + s1.name);
}
}
π Line-by-Line Code Explanation
class Student { String name; int age; }
Declares a class blueprint defining two instance fields: name (String) and age (int).
Student s1 = new Student();
Allocates a new Student object on the Heap; s1 on the Stack holds the memory address (reference).
s1.name = "Priya Sharma";
Follows the s1 reference to the Heap object and writes "Priya Sharma" into the name field.
Student s4 = s1;
Copies the memory address from s1 into s4. Both variables now point to the same Heap object.
Practical Real-World Example
class BankAccount {
String accountNumber;
String holderName;
double balance;
void showBalance() {
System.out.printf(" Account: %s | Holder: %-12s | Balance: $%,.2f%n",
accountNumber, holderName, balance);
}
}
public class PracticalApplication {
public static void main(String[] args) {
BankAccount acc1 = new BankAccount();
acc1.accountNumber = "SB-001-2026";
acc1.holderName = "Ravi Kumar";
acc1.balance = 15000.00;
BankAccount acc2 = new BankAccount();
acc2.accountNumber = "SB-002-2026";
acc2.holderName = "Priya Devi";
acc2.balance = 32500.75;
System.out.println("=== Active Bank Accounts ===");
acc1.showBalance();
acc2.showBalance();
}
}
- Accessing an object's field without first creating the object (NullPointerException).
- Writing
Student s1 = Student();without thenewkeyword, which is a compile error. - Believing that
s4 = s1creates a copy of the object. It only copies the reference address! - Declaring fields inside a method (those are local variables, NOT instance fields).
Test your understanding by writing the code directly in your editor or running in our online Java compiler:
// Coding Challenge:
// 1. Create a class Rectangle with fields: double length and double width.
// 2. Add a method calculateArea() returning length * width.
// 3. Add a method calculatePerimeter() returning 2 * (length + width).
// 4. Create 3 different Rectangle objects and display their area and perimeter.
class Rectangle {
double length;
double width;
double calculateArea() {
return length * width;
}
double calculatePerimeter() {
return 2 * (length + width);
}
}
public class Challenge {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.length = 10.0; r1.width = 5.0;
Rectangle r2 = new Rectangle();
r2.length = 8.5; r2.width = 3.0;
System.out.printf("R1: Area=%.2f, Perimeter=%.2f%n", r1.calculateArea(), r1.calculatePerimeter());
System.out.printf("R2: Area=%.2f, Perimeter=%.2f%n", r2.calculateArea(), r2.calculatePerimeter());
}
}
π‘ Frequently Asked Questions & Interview Insights
β Can we have a class without fields or methods?
Yes, Java allows an empty class (`class Empty {}`). However, it is rarely useful. Marker interfaces and some annotation types are used this way in enterprise code.
β How many objects can be created from a single class?
Theoretically unlimited, bounded only by available JVM Heap memory. A highly loaded web server might instantiate thousands of `HttpRequest` objects per second from a single class definition.
β What is the difference between a class and an object?
A class is a compile-time concept (code written in a .java file), while an object is a runtime concept (memory allocated in the JVM Heap). One class definition can produce millions of objects.
π Quick Chapter Recap
- A class is a blueprint defining fields (state) and methods (behavior).
- An object is a live instance of a class, allocated in JVM Heap memory.
newallocates the object, initializes fields to defaults, and invokes the constructor.- The dot operator (
.) navigates from a Stack reference to a Heap object's members. - Multiple objects are independent; each has its own copy of instance fields.