我已经将下面的构造函数放在一起了。我的一个问题是:如何同时使用不带参数且具有两个或三个参数的相同构造函数?有不止一种方法可以做到这一点吗?谢谢
public class bankaccount {
String firstnameString;
String lastnameString;
int accountnumber;
double accountbalance;;
public bankaccount(String firstname,String lastname){
int accountnumber=999999;
double accountbalance=0.0;
}
}
最佳答案
您需要实现您想要使用的所有变体。然后,您可以使用 this()
在构造函数之间调用,以避免代码冗余:
public class BankAccount {
public BankAccount(){
this("", "");
// or this(null, null);
}
public BankAccount(String firstname){
this(firstname, "");
// or this(firstname, null);
}
public BankAccount(String firstname, String lastname){
// implement the actual code here
}
}
顺便说一句,您应该查看Java Coding Conventions -class names (因此构造函数)以驼峰式大小写表示。
关于java - 构造函数中的多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983085/