Java – Declaring Objects

Java – Declaring Objects 2017-08-09T10:07:57+00:00

Java Declaring Objects :

The program we gave in previous topic from that we can easily learn that how object is going to declare and define for any class.

Syntax of object:

classname objectname;         \\ declaration of object.

objectname = new classname();      \\ allocate memory to object (define object).

or we can directly define object like this

classname objectname = new classname();

Now let us look one class which has two different object.


Output :
Volume is 3000.0
Volume is 162.0

From the above program we can understand that each object has its own copies of the instance variables.

This means that if you have two Box objects, each has its own copy of depth, width, and height. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another.

Assigning Object Reference Variables :


Box b1 = new Box();
Box b2 = b1;
Here b1 is the object of class Box. And we assign b1 to b2 by b2=b1.
Here we did not use new keyword for b2 so b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object.

NOTE: When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.

Prev Next