簡體   English   中英

構造函數中的多個參數

[英]Multiple parameters in 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編碼約定 -在駝峰式的情況下注明類名 (以及構造函數)。

如果您未實現任何構造函數,則將為您提供no參數構造函數。 如果要有多個構造函數,則可以自己實現所有這些構造函數。

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
  }

}

其他人建議您創建多個構造函數,這很好。 但是,在某些情況下,您可能更喜歡僅使用零參數構造函數,並使用getter和setter來訪問屬性。

您的BankAccount類可能是這些情況之一。 似乎是一個數據對象,其中的一個對象是通過使用某些ORM(例如,休眠)保留在DBMS中的。 Hibernate不需要多參數構造函數,它將調用零參數構造函數並通過getter和setter訪問屬性。

這個課程是做什么的? 它是映射到對象的數據庫實體嗎? 您是否真的需要所有這些構造函數(可能會浪費時間)?

從理論上講,我的建議可以看作是與OO設計的良好實踐抗爭,但實踐與理論有所不同。 如果您的類僅攜帶一些數據,並且構造函數不檢查所提供參數的有效性,則可以只列出屬性並使用IDE的功能來創建getter和setter。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM