OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 2 : Declaring Objects
Unit - 2
Topic 2 : Declaring and Creating Objects in Java
Declaring objects of a class is a two-step process in Java:
Step 1: Declare a reference variable
Before we can use an object, we must declare a reference variable of the class type.
This variable doesn’t create the object — it just stores the reference (memory address) of an object once it is created.
Example:
Here, mybox
is null by default (it doesn’t refer to any object yet).
Step 2: Create the object using new
To actually create the object in memory, we use the new
operator. The new
operator:
-
Allocates memory for the object.
-
Returns a reference to the object (similar to a memory address).
Example:
Combining both steps
In most cases, we combine the declaration and creation in one line:
This means:
-
Declare
mybox
as a reference to aBox
object. -
Create a
Box
object in memory and assign its reference tomybox
.
Example Program: Declaring and Creating Objects
Sample Output
Key Points to Remember
-
A class variable is just a reference; the actual object is created using
new
. -
If you declare a reference but don’t assign an object, it will be
null
. Accessing it will cause a NullPointerException. -
You can create multiple objects from the same class, each with its own data.
Example:
Here, b1
and b2
are two separate objects in memory.
Comments
Post a Comment