// 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
任何人都可以解释一下这个程序的输出吗? 我无法理解" 构造函数如何调用10 "正在打印。 在此先感谢。
答案 0 :(得分:4)
Test2
。Test1 t1 = new Test1(10);
,它使用参数10执行Test1
的构造函数并打印"构造函数10"。 Test2
构造函数的主体,其中包含t1 = new Test1(i);
,它使用参数Test1
(其值为5)执行i
的构造函数并打印"构造函数称为5"。答案 1 :(得分:0)
在Test2类中,您通过调用Test1的构造函数并传入值10来创建Test1的实例。
Test1 t1 = new Test1(10);
在它的构造函数中是一个print语句,它打印传递给构造函数的值。
Test1(int x) {
System.out.println("Constructor called " + x);
}
这是您输出的来源。