1) why "new" is not required to allocate memory for the object b?
A new B is created by the method c.xyzMethod();
public B xyzMethod(){
B b = new B();
b.setI(10);
return b;
}
As you can see a fully functional B is created by this method, memory allocated for it and a reference to it is passed. Object A is fully entitled to keep a reference to this object. There is no difference between this and both declaring a variable and initialising an object on a single line
2) Is my probable answer is correct? If its correct, why have we allocated memory to object c using new? Perhaps, its due the reason that "this" was to be passed to the object. So for proper initialization we used new with argument "this".
It is important to remember that object A does not need to allocate memory for object B, all class A needs is memory for a reference to object B. Object B can be kept elsewhere and many A
s can share the same B
(although this isn't the case in your code)
3) If I am correct at point 2 above, what does happen to the previously allocated memory to object c as new will allocate new chunk of memory and assign the new address to c? Garbage collected?
Assuming there are no references to that object elsewhere (which is the case in your code) it will indeed become eligible to be garbage collected
4) So from above points, we can say memory is allocated for the objects which are members of a containing class, at the time of object creation of the containing class. And we can directly assign value to them we out calling new on them?
Although practically you can consider objects to "contain" other objects this is just a human way of looking at it. For example the following circular dependency is perfectly fine (although sometimes unwise):
public class A {
private B b;
public A() {
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public void main(String[] args){
A a=new A();
B b=new B();
a.setB(b);
b.setA(a);
//because all that a and b contain is references this circular referencing
//doesn't blow up
//this line is stupid, but perfectly valid
A referenceToAnA=b.getA().getB().getA().getB().getA();
}
}
public class B {
private A a;
public B() {
}
public void setA(A a) {
this.a = a;
}
public A getA() {
return a;
}
}
Final notes
Just like in C++ you must allocate memory for a new object by using the new keyword, it is however, not necessary to deallocate that memory, garbage collection deals with that