簡體   English   中英

構造函數調用必須是第一個語句…錯誤,但不是構造函數

[英]Constructor call must be first statement…error, but it is NOT a constructor

好的,另一個Constructor call must be first statement in a constructor錯誤中的Constructor call must be first statement in a constructor ...唯一的區別是,我在不是構造函數的方法中遇到此錯誤...

下面是我的代碼:

public DamnEclipse extends Duh {
    private String title;

    private DamnEclipse(String title) {
        this.title = title;
    }

    public static DamnEclipse initWithTitle(String title) {
        return this(title); //this is where the error occurs
        // this(title); also gives the same error
    }
}

作為記錄,私有構造函數可以正常工作(沒有錯誤...)。 首先, initWithTitle(String title)不是構造函數。 其次,類Duh沒有指定構造函數。

我覺得這對我的Java知識或者只是日食都是非常愚蠢的。 有任何想法嗎?


更新:我可以使用以下代碼:

public static DamnEclipse initWithTitle(String title) {
    return new DamnEclipse(title);
}

但是我仍然想知道為什么以前的那個不起作用!

像@Ramanlfc一樣:

this關鍵字在static方法中不可用

但是,您也不能從構造函數外部調用this(title)的構造函數。 這只是無效的Java。

如果要返回包含類的新實例,則需要使用new和類名,就像在其他任何地方創建實例一樣:

return new DamnEclipse(title);

如果您想知道為什么您的代碼是無效的Java,請查閱語法:

ConstructorBody:
  { [ExplicitConstructorInvocation] [BlockStatements] }

ExplicitConstructorInvocation:
  [TypeArguments] this ( [ArgumentList] ) ; 
  [TypeArguments] super ( [ArgumentList] ) ; 
  ExpressionName . [TypeArguments] super ( [ArgumentList] ) ; 
  Primary . [TypeArguments] super ( [ArgumentList] ) ;

MethodBody:
  Block 
  ;

因此, ConstructorBodyMethodBody實際上是兩種完全不同的語法類型。 只有ConstructorBody包含ExplicitConstructorInvocationthis(something)允許您調用this(something) 在構造函數外部調用this(something)在語法上根本無效。

 public static DamnEclipse initWithTitle(String title) {
        return this(title); //this is where the error occurs
        // this(title); also gives the same error
    }

this關鍵字在static方法中不可用

因此,當您調用公共靜態函數時,{this}關鍵字不會引用父類(DamEclipse類)。 在靜態上下文中不允許使用{this}關鍵字。 這就是為什么當您返回新的DamnEclipse時它會起作用的原因。 它創建一個對象。

暫無
暫無

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

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