为什么这个类有两个构造函数?

Abd*_*ahR 5 java methods constructor class

我在幻灯片中看到了这一点,旨在说明构造函数.我现在很困惑,因为它有两个具有相同作业的构造函数接受在第二个中将gpa设置为零.为什么编码器需要重复this.id = id; this.name = name;?为什么这个类甚至需要两个构造函数?

class Student{
      private int id;
      private String name;
      private double gpa;
      public Student(int id, String name, double gpa){
        this.id = id;  this.name = name;   this.gpa = gpa;
      }
      public Student(int id, String name){
        this.id = id;  this.name = name;   gpa = 0.0;
      }
      public boolean equals(Student other){
          return id == other.id && name.equals(other.name) 
                       && gpa == other.gpa;
      }
      public String toString(){
        return name + " " + id + " " + gpa;
      }
      public void setName(String name){
        this.name = name;
      }
      public double getGpa(){
        return gpa;
      }
    }
Run Code Online (Sandbox Code Playgroud)

akf*_*akf 12

与大多数人为的例子一样,除了表明超载是可能的之外,通常没有明显的理由.在这个例子中,我很想重构第二个构造函数,如下所示:

 public Student(int id, String name){
    this( id, name, 0.0 );
  }
Run Code Online (Sandbox Code Playgroud)


Cem*_*mre 0

构造函数被重载(相同的名称和返回类型,但具有不同的参数,即不同的签名),以便您可以以不同的方式启动该类的实例。一本具有您选择的 GPA,另一本具有默认 GPA 0.0