The most fundamental concept in OOP is the distinction between a Class and an Object. Understanding this relationship is the key to mastering every other OOP principle.
A Class is a user-defined blueprint or prototype from which objects are created. It defines a set of attributes (variables) and methods (functions) that the created objects will have.
Think of a class as an architectural blueprint for a house. The blueprint itself is not a house—you cannot live in a blueprint. It simply defines the structure: how many rooms, where the doors go, and where the plumbing runs.
// The Blueprint (Class)
class Car {
// Attributes (State)
String brand;
String color;
int speed;
// Methods (Behavior)
void accelerate() {
this.speed += 10;
}
void brake() {
this.speed -= 10;
}
}
An Object is a specific instance of a class. It is a concrete entity that exists in memory, holds actual values for the attributes defined in the class, and can execute the methods.
If the Car class is the blueprint, then a specific red Toyota with a speed of 60 km/h is an Object (an instance) of that class.
The process of creating an object from a class is called Instantiation. In most OOP languages, this is done using the new keyword.
// Instantiation: Creating actual Objects from the Class
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.color = "Red";
Car yourCar = new Car();
yourCar.brand = "BMW";
yourCar.color = "Black";
When new Car() is executed:
Car class.null for Strings, 0 for integers).myCar.this KeywordInside a method, how does the object know which object's data it should operate on? When you call myCar.accelerate(), the Java runtime implicitly passes a hidden reference to myCar into the accelerate() method. This hidden reference is accessed via the this keyword.
void accelerate() {
this.speed += 10; // 'this' refers to whichever object called the method
}
It is crucial to understand the difference between the reference variable and the actual object:
myCar (which is just a memory address pointer) is stored on the Stack.When you write Car anotherRef = myCar;, you are NOT creating a new car. You are copying the memory address. Both anotherRef and myCar now point to the exact same object on the Heap. Modifying the car through one reference will be visible through the other.