构造函数中的多个参数

2 java class-constructors

我把下面的构造函数放在一起.我的一个问题是:如何使用相同的构造函数,没有参数,同时使用两个或三个?有不止一种方法可以做到这一点吗?谢谢

public class bankaccount {

  String firstnameString;
  String lastnameString;
  int accountnumber;
  double accountbalance;;

  public bankaccount(String firstname,String lastname){
    int accountnumber=999999;
    double accountbalance=0.0;
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ter 6

您需要实现要使用的所有变体.然后,您可以使用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
  }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您应该查看Java编码约定 - 类名称(以及构造函数)在camel case中注明.