Classes and Objects in Java
Introduction
Java is fundamentally an Object-Oriented Programming (OOP) language. In Java, everything is centered around Objects and Classes. Understanding the relationship between these two concepts is the first and most crucial step to mastering Java.
What is a Class?
A Class is a blueprint, template, or prototype that defines the state and behavior of objects of a certain kind. It is a logical entity; it does not consume memory when it is defined.
A class typically contains:
- Fields (State): Variables that hold data.
- Methods (Behavior): Functions that define what the object can do.
- Constructors: Special methods used to initialize new objects.
Example: Defining a Class
// The Blueprint
public class Car {
// 1. Fields (State)
String color;
String model;
int speed;
// 2. Constructor
public Car(String color, String model) {
this.color = color;
this.model = model;
this.speed = 0; // Default speed
}
// 3. Methods (Behavior)
public void accelerate() {
speed += 10;
System.out.println(model + " is accelerating. Speed: " + speed);
}
}
What is an Object?
An Object is a physical or logical entity that has state and behavior. It is an instance of a class. When an object is created from a class, memory is allocated on the Heap.
You can create multiple independent objects (instances) from a single class blueprint.
Example: Creating an Object (Instantiation)
To create an object in Java, you use the new keyword, which allocates memory at runtime and calls the constructor.
public class Main {
public static void main(String[] args) {
// Creating an Object (Instance) of the Car class
Car myTesla = new Car("Red", "Tesla Model 3");
// Creating another independent Object
Car myFord = new Car("Blue", "Ford Mustang");
// Accessing methods
myTesla.accelerate(); // Output: Tesla Model 3 is accelerating. Speed: 10
myFord.accelerate(); // Output: Ford Mustang is accelerating. Speed: 10
}
}
The "new" Keyword and Memory
When you execute Car myTesla = new Car("Red", "Tesla Model 3");, three things happen under the hood:
- Declaration:
Car myTesladeclares a reference variable namedmyTeslaof typeCar. This variable lives on the Stack memory. - Instantiation: The
newkeyword dynamically allocates physical memory on the Heap for the new object. - Initialization: The constructor
Car(...)is called to initialize the object's fields. The reference variablemyTeslais then pointed to this newly allocated memory on the Heap.
Null Reference Exception
If you declare an object but forget to use the new keyword, the variable does not point to any memory location (it is null). Attempting to access its methods or fields will result in a NullPointerException.
Car brokenCar; // Declared, but not instantiated (null)
// brokenCar.accelerate(); // CRASH! Throws NullPointerException