JAVA一个类有两个构造函数,当在一个构造函数中调用另外一个构造函数时为什么要用this.()而不能用类名.()
class Test{ int i; Test(){ i = 0; } Test(int i){ this.();} } 我的意思是此处第二个构构造函数调用第一个构造函数时为什么必须用this.()而不能用Test.()
打错了 是this() 和 类名() 多打了一点
专业回答
构造方法是在产生对象时被java系统自动调用的,我们不能在程序中像调用其他方法一样去调用构造方法(必须通过关键词new自动调用它)。但我们可以在一个构造方法里调用其他重载的构造方法,不是用构造方法名,而是用this(参数列表)的形式,根据其中的参数列表,选择相应的构造方法。例如:
public class Person{
String name;
int age;
public Person(String name){
this.name = name;
}
public Person(String name,int age){
this(name);
this.age = age;
}
}
public class Person{
String name;
int age;
public Person(String name){
this.name = name;
}
public Person(String name,int age){
this(name);
this.age = age;
}
}