What is an Object?
About
In Java, an object is an instance of a class that contains state (fields/variables) and behavior (methods). Objects are created based on the blueprint defined by a class.
Characteristics of an Object
State (Attributes)
Represented by instance variables (fields).
Stores the data or properties of the object.
Behavior (Methods)
Defined by functions inside the class.
Determines what actions an object can perform.
Identity (Reference)
Each object has a unique memory address in the heap.
Example of an Object
How Objects Work in Memory
Objects are created in the heap memory.
The reference variable (like
car1
andcar2
) points to the object in memory.Multiple reference variables can point to the same object.
When is the object created with new keyword
In Java, the object is created with the new
keyword during runtime.
The new
keyword plays a crucial role in the object creation process:
Memory Allocation: It triggers the allocation of memory for the new object on the heap. The heap is a special area of memory dedicated to storing objects in Java.
Constructor Call: It invokes the constructor of the class specified after
new
. The constructor is responsible for initializing the object's state by assigning values to its fields.
Therefore, the new
keyword initiates object creation and memory allocation at runtime, not during compilation. This allows for dynamic object creation based on your program's needs.
Last updated
Was this helpful?