0
Please someone help me to understand the flow of this program.
class A { B obj; A(B obj) { this.obj = obj; obj.display(); } } class B { int x = 5; B() { A obj = new A(this); } void display() { System.out.println("Value of x in Class B : " + x); } public static void main(String[] args) { B obj = new B(); } } https://code.sololearn.com/c2VZ1ZNAglnE
5 Respuestas
+ 3
Beginning from the main method-
B obj = new B();
This creates an object of type B.
Moving to class B-
B()
{
A obj = new A(this);
}
This is called and here you create an object of type A. The 'this' keyword is a reference to the current object which was created in the main method.
Moving on to class A-
A(B obj)
{
this.obj = obj;
obj.display();
}
This is called since you created an instance of A in constructor of class B.
Here you have passed the reference of the current object to 'obj' and a B type object is initialized with the same reference to the one in the main method.
obj.display();
This will call the display method from class B and the value of 'x' is displayed.
+ 1
Where does you haven't understood ?
+ 1
Tushar 'obj' is an object of class B. Read my explanation 'Moving on to class A'.
0
@Franck Heuba
B()
{
A obj = new A(this);
}
this part brother...
0
@Avinesh Thank you...It helped me to understand.
But I have doubt...Isn't we are only supposed to call method from it's class object only?
But In the above program we have an Object of Class A named "obj" , and calling display method from class B. WHY?