Please someone help me to understand the flow of this program. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
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

6th May 2020, 4:03 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
5 ответов
+ 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.
6th May 2020, 5:20 PM
Avinesh
Avinesh - avatar
+ 1
Where does you haven't understood ?
6th May 2020, 4:05 PM
HEUBA BATOMEN Franck Duval
HEUBA BATOMEN Franck Duval - avatar
+ 1
Tushar 'obj' is an object of class B. Read my explanation 'Moving on to class A'.
6th May 2020, 11:05 PM
Avinesh
Avinesh - avatar
0
@Franck Heuba B() { A obj = new A(this); } this part brother...
6th May 2020, 5:06 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
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?
6th May 2020, 10:37 PM
I Am a Baked Potato
I Am a Baked Potato - avatar