Java2all.com  

Declaring Objects





Share This Topic -

How to declare object of class in java?

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.

 class Box 
{
        double width;
        double height;
        double depth;
}
class BoxDemo2 
{
        public static void main(String args[]) 
       {
             Box mybox1 = new Box();
             Box mybox2 = new Box();
             double vol;
             // assign values to mybox1's instance variables
             mybox1.width = 10;
             mybox1.height = 20;
             mybox1.depth = 15;
             /* assign different values to mybox2's instance variables */
             mybox2.width = 3;
             mybox2.height = 6;
             mybox2.depth = 9;
             // compute volume of first box
             vol = mybox1.width * mybox1.height * mybox1.depth;
             System.out.println("Volume is " + vol);
             // compute volume of second box
            vol = mybox2.width * mybox2.height * mybox2.depth;
            System.out.println("Volume is " + vol);
       }
}

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 :

 

Suppose 
 
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.