java - 构造函数中的多个参数

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

最佳答案

您需要实现您想要使用的所有变体。然后,您可以使用 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/

相关文章:

java - 没有 volatile 关键字的原子语句被忽略

Kotlin 主构造函数调用辅助构造函数

python - Python 3 中默认的 `` `__new_ _`` ` 是什么?

c++ - 在构造函数定义中调用函数后收到 Segmentation Fault 11 错误?

java - 行选择在 JTable 中不起作用

java - Spring Test DBUnit 和表架构名称

java - 反转通用列表中的项目

java - Fragment onClick调用方法

c# - 功能(): this(null) {}