簡體   English   中英

在Java抽象類中初始化“默認”最終屬性

[英]Initializing “Default” final attributes in Java abstract class

我有一個抽象類,應該具有一個(int)屬性,該屬性在初始化后不能修改,並且預設為1; 最好的方法是什么? 我應該做最后嗎? 要求是在類內部,我將只有一個構造函數(帶有參數),並且沒有設置方法。 如果是這樣的話,如果它是最終版本,並且我將如何在構造函數中對其進行初始化,那么如何默認將其設置為1? 謝謝!

您應該使用帶有參數的構造函數來設置初始值。 然后,就像您所說的,不要創建任何設置器,並確保您的字段是私有的,以便沒有人可以訪問它。

這樣,您將做自己想要的事情,初始化字段,但此后再也不會更改。

事實上,如果它始終是一個恆定值,您甚至可以對其進行硬編碼。

例如,如果變量應始終為25,則可以執行以下操作:

public abstract class Test
{
  protected final int pressure = 25;

  //Constructor
  public Test()
  {
    // TODO Auto-generated constructor stub
  }
}

但是,如果在運行時評估值,則需要在Object的構造函數中進行設置:

public abstract class Test
{
  protected final int pressure;

  //Constructor
  public Test(int pressure)
  {
    this.pressure = pressure;
  }
}

請注意,在這種情況下, 不得更早分配變量!

是否應使用最終變量的問題取決於其目的。 最終變量在整個生命周期中只能分配一次。 如果必須進行任何修改,則不應使用。

您可以使用構造函數重載來實現這一點。 參見示例:

public abstract class TestClass{

  private final int otherParam;
  private final int fixedParam;

  public TestClass(final int otherParam){
    this.otherParam = otherParam;
    this.fixedParam = 1;
  }

  public TestClass(final int otherParam, final int fixedParam){
    this.otherParam = otherParam;
    this.fixedParam = fixedParam;
  }

}

暫無
暫無

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

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