-
Notifications
You must be signed in to change notification settings - Fork 137
Java Objects
-
An object is a runtime instance of a Java class. While a class defines the structure and behavior of an entity, an object is the actual implementation of that definition in memory. Objects are the fundamental building blocks of Java applications, allowing programs to represent and manipulate real-world entities such as people, vehicles, bank accounts, or products.
-
A class by itself does not occupy memory for its instance variables. Memory is allocated only when an object is created. Each object maintains its own state (data) while sharing the behavior (methods) defined by its class.
-
For example, a Car class may define fields such as brand, model, and year, along with methods like start() and stop(). When you create an object from this class, the JVM allocates memory for that specific car, giving it its own set of field values while reusing the methods defined by the class.
When an object is created, the Java Virtual Machine (JVM) performs several operations behind the scenes:
- Allocates memory on the Heap.
- Initializes instance variables with their default values.
- Executes instance initialization blocks (if present).
- Executes the selected constructor.
- Returns a reference to the newly created object.
An object is created using the new keyword.
Car myCar = new Car();
This statement performs three actions:
- Declares a reference variable named myCar.
- Creates a new Car object in the heap.
- Assigns the object's reference (memory address) to myCar.
flowchart TD
A["Class Definition"] --> B["new Keyword"]
B --> C["Memory Allocated in Heap"]
C --> D["Default Values Assigned"]
D --> E["Instance Initialization Blocks"]
E --> F["Constructor Execution"]
F --> G["Object Reference Returned"]
Each object has a unique identity that distinguishes it from all other objects, even if they contain identical data.
Example
Car car1 = new Car();
Car car2 = new Car();Although both objects are created from the same class, they are two different objects stored at different memory locations.
Memory representation:
Stack
──────────────
car1 ─────┐
│
▼
Heap
──────────────
Car Object A
──────────────
Stack
──────────────
car2 ─────┐
│
▼
Heap
──────────────
Car Object B
──────────────
Comparison:
System.out.println(car1 == car2);Output
false
Even though both objects are created from the same class, they have different identities.
The state of an object is represented by the values stored in its instance variables.
Example
public class Car {
String brand;
String model;
}Car car1 = new Car();
car1.brand = "Toyota";
car1.model = "Corolla";
Car car2 = new Car();
car2.brand = "Honda";
car2.model = "Civic";Memory representation:
Car Object 1
--------------------
brand = Toyota
model = Corolla
Car Object 2
--------------------
brand = Honda
model = Civic
Although both objects belong to the same class, each maintains its own independent state.
Behavior refers to the actions an object can perform, which are defined by the methods of its class.
Example
public class Car {
public void start() {
System.out.println("Car started.");
}
public void stop() {
System.out.println("Car stopped.");
}
}Using the object:
Car car = new Car();
car.start();
car.stop();Output
Car started.
Car stopped.
Every object created from the Car class inherits the same behavior defined by its methods. Although each object may have different data (state), they can all perform the same operations.
An object's lifecycle generally consists of the following stages:
- Declaration of a reference variable.
- Object creation using new.
- Memory allocation in the heap.
- Constructor execution.
- Object usage.
- Becoming unreachable.
- Garbage collection.
Java supports different kinds of objects depending on how they are created or used.
| Object Type | Description | Example |
|---|---|---|
| Regular Object | A standard object created using the new keyword. This is the most common type of object in Java. |
Car car = new Car(); |
| Anonymous Object | An object created without assigning it to a reference variable. It is typically used for one-time operations. | new Car().start(); |
| Singleton Object | An object of a class that is designed to have only one instance throughout the application's lifetime. | DatabaseConnection connection = DatabaseConnection.getInstance(); |
| Immutable Object | An object whose state cannot be changed after it has been created. Any modification results in a new object. | String message = "Hello"; |
| Mutable Object | An object whose state can be modified after creation. Most user-defined classes are mutable by default. | StringBuilder builder = new StringBuilder(); |
| Wrapper Object | An object that wraps a primitive data type, allowing primitives to be treated as objects. | Integer number = Integer.valueOf(100); |
| Array Object | An object used to store multiple values of the same type. Arrays are objects in Java and inherit from the Object class. |
int[] numbers = {1, 2, 3, 4}; |
| Enum Object | A predefined object representing one of a fixed set of constants declared in an enum. |
Day today = Day.MONDAY; |
| Record Object | An immutable object created from a Java record, primarily used for modeling data. |
Student student = new Student("Alice", 20); |
| Class Object | A special object representing metadata about a class at runtime. It is commonly used with reflection. | Class<?> cls = String.class; |
new Car().displayInfo();
The object is created, used once, and then becomes eligible for garbage collection if no reference exists.
- An object is a runtime instance of a class.
- Objects are created using the new keyword.
- Objects are stored in the heap.
- Variables store references to objects.
- Each object has its own state but shares the class's behavior.
- Multiple objects can be created from a single class.
- Objects are managed by the JVM and automatically reclaimed by the Garbage Collector when no longer reachable.