构造方法:Java 类中的构造方法用于初始化对象,从语法上来说,和普通的方法相比,没有返回类型,名称和类名相同,通过 new 关键字调用,执行后返回的是类的实例对象。
方法重载:方法名相同、参数不同的多个方法称为重载方法。Java 虚拟机会根据参数选取合适的方法调用。参数少的方法调用参数多的重载方法是个减少代码量的小技巧。
this:this 关键字可用于在构造方法中调用其他构造方法。
根据上面的规则帮你修改代码如下:
public class Person {
public String name;
public int age;
public String school;
public String major;
public Person(String n, int a) {
this(n, a, null);
}
public Person(String n, int a, String s) {
this(n, a, s, null);
}
public Person(String n, int a, String s, String m) {
this.name = n;
this.age = a;
this.school = s;
this.major = m;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", school='" + school + '\'' +
", major='" + major + '\'' +
'}';
}
}
public class Test {
public static void main(String[] args) throws SQLException, IOException {
Person p1 = new Person("小明", 10);
Person p2 = new Person("小明", 10, "大学");
Person p3 = new Person("小明", 10, "大学", "机械专业");
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}