构造函数中的多个参数

时间:2013-02-20 15:05:56

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

3 个答案:

答案 0 :(得分: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
  }
}

顺便说一句,你应该查看Java Coding Conventions - class names(因此构造函数)在驼峰案例中注明。

答案 1 :(得分:0)

如果未实现任何构造函数,则为您提供无参数构造函数。如果你想拥有多个构造函数,那么你自己就可以实现所有这些构造函数。

public class bankaccount {

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

  public bankaccount(String firstname,String lastname){
    int accountnumber=999999;
    double accountbalance=0.0;
  }

  public bankaccount(){
    // put code here, or call this(null,null) / a different constructor
  }

}

答案 2 :(得分:0)

其他人建议你创建多个构造函数,这很好。但是,在某些情况下,您可能更喜欢只使用零参数构造函数,并使用getter和setter来访问属性。

您的BankAccount课程可能是其中一种情况。它看起来像一个数据对象,其中一个对象通过使用一些ORM(例如Hibernate)持久存储到DBMS中。 Hibernate不需要多参数构造函数,它将调用零参数构造函数并通过getter和setter访问属性。

这堂课是为了什么?它是映射到对象的数据库实体吗?你真的需要所有这些结构(这可能是浪费时间)吗?

从理论上讲,我的建议可以被认为是对抗OO设计良好实践的斗争,但实践与理论有所不同。如果您的类只携带一些数据,并且构造函数不会检查所提供参数的有效性,那么您只需列出属性并使用IDE的工具来创建getter和setter。