Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this class have two constructors?

I see this in the slide that aims to illustrate constructors. I'm confused now because it has two constructors that have the same job accept setting gpa to zero in the second one. Why does the coder need to repeat this.id = id; this.name = name; again? 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;
      }
    }
like image 399
AbdullahR Avatar asked Jan 14 '12 02:01

AbdullahR


2 Answers

As with most contrived examples, there is often no obvious reason other than to show that the overloading is possible. In this example, I would be tempted to refactor the second constructor like this:

 public Student(int id, String name){
    this( id, name, 0.0 );
  }
like image 135
akf Avatar answered Oct 19 '22 18:10

akf


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

Having more than 1 constructor(same name and return type(constructor has class type as its default return type)) but with different parameters(different signature)

parameters of overloaded constructors or methods can vary in type and number of parameters...and even the sequence

the instances of the class / objects that you create invokes constructors at time of creation.. so at that time you could provide 2 or 3 parameters depending upon which constructor you want to use.. if you provide 3 it uses 3 parameter constructor..and 2 parameters then it uses 2 parameter constructor

It is basically the need of sometimes providing gpa or sometimes not.. therefore having initialization of objects with different values..

like image 36
riteshtch Avatar answered Oct 19 '22 18:10

riteshtch