如何制作构造函数,如果有 2 个参数,则接受 2;如果有 3 个参数,则接受 3
Java 新手...
我有一个名称类,其中包含:
private String firstName;
private String middleInitial;
private String lastName;
作为其实例变量。
如果我的某些数据只有firstName和lastName,没有middleInitial,我将如何创建构造函数,使其只需要2个参数而不是3个?
New to Java...
I have a name class that has:
private String firstName;
private String middleInitial;
private String lastName;
as its instance variables.
If I had certain data that had only firstName and lastName, no middleInitial, how would I make the constructor so that it took only 2 parameters instead of three?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您只需编写一个具有两个参数的构造函数和一个具有三个
调用者的构造函数,然后调用者就可以根据自己的需要选择使用适当的构造函数。
You simply write a constructor with two parameters and a constructor with three
Callers can then choose to use the appropriate constructor based on their needs.
好吧,有两种选择:
middleInitial
的空字符串来调用它。作为后者的示例,使用空字符串作为默认的中间名首字母:
但是,编译器需要知道您正在从调用站点调用哪一个。所以你可以这样做:
或
...但你不能这样做:
并期望编译器决定使用“两个名称”变体。
Well, two options:
middleInitial
As an example for the latter, using an empty string as the default middle initial:
However, the compiler will need to know which one you're calling from the call site. So you can do:
or
... but you can't do:
and expect the compiler to decide to use the "two name" variant instead.
在 Java 中,构造函数不能有默认参数。这里唯一的选择是编写两个构造函数。幸运的是,Java 允许您从其他构造函数调用构造函数。你可以这样做:
In Java, constructors can't have default arguments. Your only option here is to write two constructors. Fortunately, Java does allow you to call constructors from other constructors. You could do something like:
您可以使用两个构造函数:
You could use two constructors:
定义 2 个构造函数,一个有 2 个参数,一个有 3 个参数。
Define 2 constructors, one with 2 parameters and one with 3 parameters.
您可以编写两个构造函数。
You can write two constructors.
建造者模式...
Builder pattern...