Classes & Objects
TL;DR
- Class: A blueprint, template, or prototype from which objects are created. It defines properties (fields) and behaviors (methods).
- Object: An instance of a class. It represents a real-world entity that has state (data) and behavior (functionality) defined by its class.
Concept
Object-Oriented Programming (OOP) revolves around objects rather than logic, and data rather than functions.
The Blueprint (Class)
A class is a logical construct. It does not consume any memory space for data (except when the class itself is loaded). It defines what an object of that type will look like.
The Instance (Object)
An object is a physical reality in memory (allocated on the Heap). You can create as many objects as you want from a single class. Each object has its own unique copy of the instance variables defined in the class.
Examples
// 1. Creating the Class (Blueprint)
class Car {
// Fields (State)
String color;
int speed;
// Methods (Behavior)
void accelerate() {
speed += 10;
System.out.println("Accelerating. Speed is now " + speed);
}
}
public class Main {
public static void main(String[] args) {
// 2. Creating Objects (Instances) using the 'new' keyword
Car myTesla = new Car();
myTesla.color = "Red";
myTesla.speed = 0;
Car myFord = new Car();
myFord.color = "Blue";
myFord.speed = 20;
// 3. Invoking Behavior
myTesla.accelerate(); // myTesla's speed becomes 10
myFord.accelerate(); // myFord's speed becomes 30
}
}
Interview Questions
Q: What happens in memory when you use the new keyword?
A: The new keyword triggers memory allocation on the Heap for the new object. It initializes the object’s instance variables to their default values (e.g., 0 for ints, null for references) and then calls the class constructor to perform any developer-defined initialization. Finally, it returns a memory reference to that newly created object.
Q: Can an object exist without a class?
A: In Java, no. Java is a class-based object-oriented language. Every object must be an instance of a predefined class. (Unlike prototype-based languages like JavaScript, where objects can exist without formal classes).