Please explain this program | SoloLearn: Learn to code for FREE!

0

Please explain this program

class Robot { int id; Robot(int i) { id = i; Brain b = new Brain(); b.think(); } private class Brain { public void think() { System.out.println(id + " is thinking"); } } } public class Program { public static void main(String[] args) { Robot r = new Robot(1); } }

10/15/2019 12:48:51 AM

Priyanka Gotugade.

1 Answer

New Answer

+2

Let's start with object calling of robot class. In class program where our main define the program starts from here. And we are calling class robot object and giving it parameter to 1 ie Robot(1); Now when compiler goes to class robot it implicitly call the constructor and give value 1 to i, now that i is equal to id now id is now equal to 1 . And in customer of robot class we are calling private class brain which is not inherited but *brain class is not any another class it's nested class so main class can create object of it's nested class and calls it* Then when compiler goes to class brain , think() is one of the member function of class brain and it's printing (id+" is thinking"); While our id. =1 Therefore, this program output will be Output: 1 is thinking