views:

90

answers:

3

Consider the following inheritance example:

class A {...}  
class B extends A  
{  
 ..  
 ..  
 private static void main(String[] s)  
 {  
    A a1 = new A();  
    B b1 = new B();  
    B b2 = b1;             // What if it was B b2 = new B(); b2 = b1;  
 }
}

My question is in the comment. Would it be different, in the sense that, using the new operator creates a new space for the object b2 and b2=b1 would just copy the data of b1 into b2. So any changes done to one object won't affect the other. In the main inline code, B b2 = b1 would point b2 to the space allocated for b1. So any changes here would affect both the object data.

My query is, will using the new operator make any difference to the object manipulation?

+2  A: 

This makes an A object and a B object. There are two references to the B object.

A a1 = new A();
B b1 = new B();
B b2 = b1;

This makes an A object and two B objects. There are two references to the first B object. The second B object no longer has a reference to it and will be available for garbage collection.

A a1 = new A();
B b1 = new B();
B b2 = new B();
B b2 = b1;

B b2 = b1; No object data is every copied in this step. Both b2 and b1 will point to the same object. So it will not make a difference which you use to set or get data.

B b2 = new B();
B b2 = b1;
b2.setValue("Foo");
b1.getValue(); // would return "Foo"
unholysampler
+2  A: 
B b1 = new B()

creates a new object and assigns a reference to it, b1.

B b2 = b1

creates a new reference and sets it equal b1, which is a reference.

There is no "copy the data of b1 into b2". Two reference now point to the same underlying object.

hvgotcodes
+9  A: 
B b1 = new B();
B b2 = b1;

Above code creates only one object of type B. b1 and b2 are references that point to that same object. They are aliases to the same object.

B b1 = new B(); //1
B b2 = new B(); //2
b2 = b1;        //3

In this code, two objects of type B are created at lines 1 and 2. However, after line 3, b2 references the same object as b1 and both are thus again aliases. The object originally referenced by b2 now becomes eligible for garbage collection.

So, in both cases, b1 and b2 point to the same object and any changes done to that object will be seen through both the references. Keep in mind that b1 and b2 are not the object themselves but only references to that object. b1=b2 doesn't copy any values from one object to the other, it simply repoints the reference.

Samit G.