为什么这个类有两个构造函数? [英] Why does this class have two constructors?

查看:203
本文介绍了为什么这个类有两个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
      }
    }


推荐答案

与大多数设计的例子,除了显示超载是可能的,通常没有明显的理由。在这个例子中,我会想像这样重构第二个构造函数:

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 );
  }

这篇关于为什么这个类有两个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆