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

编程入门 行业动态 更新时间:2024-10-28 13:28:18
本文介绍了为什么这个类有两个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在幻灯片中看到这个目的是为了说明构造函数。我现在很困惑,因为它有两个构造函数有相同的工作接受设置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 ); }

更多推荐

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

本文发布于:2023-11-25 16:41:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   有两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!