一个类的构造器不能调用这个类中的其他构造器。( )
public class Constructor {
public static void main(String[] args) {
Person person = new Person("Harvay",20);
System.out.println("person = " + person);
}
}
class Person {
private String name;
private int age;
private char gender;
public Person(String name, int age) {
this(name, age, '男');
}
public Person(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
'}';
}
} 学的时候老师把这个叫做 兄弟构造器
在创建对象的时候不想赋这么多值,除了set方法还可以以这种方式创建对象
运行结果:
public class ATest { public int t1; public int t2; public ATest(int t1){ this.t1 = t1; } // 利用this可以复用构造方法 public ATest(int t1, int t2){ this(t1); this.t2 = t2; } public static void main(String[] args) { ATest at1 = new ATest(1); System.out.println(at1.t1); ATest at2 = new ATest(1,2); System.out.println(at1.t1+" "+at1.t2); } }
在Java中,一个类的构造器是可以调用同一个类中的其他构造器的,通过使用关键字 this 来实现。使用 this 关键字可以在一个构造器内部调用同一类中的其他构造器,从而避免了代码重复的问题。例如:
public class MyClass {
private int x;
private int y;
public MyClass(int x) {
this(x, 0);
}
public MyClass(int x, int y) {
this.x = x;
this.y = y;
}
} 在上面的代码中,第一个构造器调用了同一个类中的第二个构造器,通过使用 this 关键字来避免了重复的代码。