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?
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.In this code, two objects of type
Bare 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.