简体   繁体   中英

Unable to understand program work flow

// filename: Test2.java
class Test1 {   
    Test1(int x) {
        System.out.println("Constructor called " + x);
    }
}

// This class contains an instance of Test1 
class Test2 {    
    Test1 t1 = new Test1(10);   

    Test2(int i) { t1 = new Test1(i); } 

    public static void main(String[] args) {    
         Test2 t2 = new Test2(5);
    }
}

Output:
Constructor called 10
Constructor called 5

Can anyone pls explain me the output of this program? I am not able to get how " Constructor called 10 " is getting printed. Thanks in Advance.

  • Your main invokes the constructor of Test2 .
  • Before the body of that constructor is executed, all the instance variables of that class are initialized.
  • This includes Test1 t1 = new Test1(10); which executes the constructor of Test1 with the argument 10 and prints "Constructor called 10".
  • Only then the body of the Test2 constructor is executed, which includes t1 = new Test1(i); , which executes the constructor of Test1 with the argument i (whose value is 5) and prints "Constructor called 5".

In your Test2 class you have created an instance of Test1 by calling Test1's constructor and passing in a value of 10.

Test1 t1 = new Test1(10);

Inside it's constructor is a print statement that prints the value passed into the constructor.

Test1(int x) {
    System.out.println("Constructor called " + x);
}

This is where your output is coming from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM