Why does this class have two constructors?

I see this on a slide whose purpose is to illustrate the constructors. I am confused now because it has two constructors that have the same job, which take the gpa parameter equal to zero in the second. Why does the encoder need to repeat again this.id = id; this.name = name;? Why does this class even need two constructors?

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;
      }
    }
+5
source share
6 answers

As with most far-fetched examples, there is often no obvious reason but to show that overload is possible. In this example, I will be tempted to reorganize the second constructor as follows:

 public Student(int id, String name){
    this( id, name, 0.0 );
  }
+11

There are two constructors as it shows the concept of constructor overloading:

( ( )), ( )

...

/ . 2 3 , . 3, 3 .. 2 , 2

gpa, . .

+2

( i.e ), -. GPA, , GPA 0.0

0

2 , Student,

Student s = new Student(1, "Bob");

Student s = new Student(1, "Bob", 4.0);
0

, . , , , .

, GPA, 0.0 (, ). , - GPA, .

0

Suppose student promotion requires the presence of gpa, which must be present when adding a student, in which case you will create

Student s = new Student(5,"stud1",4.0);

Suppose some class promotions do not require gpa when promoting, then your student object will be Student s= new Student(6,"stud2");, which implies that the gpa students are ZERO.

0
source

All Articles