构造函数调用必须是第一个语句...错误,但它不是构造函数

时间:2016-03-15 00:04:35

标签: java eclipse 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知识或者只是eclipse都是非常愚蠢的。有什么想法吗?

更新:我使用以下代码:

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

但我仍然想知道为什么之前的那个不起作用!

3 个答案:

答案 0 :(得分:3)

像@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包含ExplicitConstructorInvocation,这就是允许您拨打this(something)的权限。在构造函数之外调用this(something)在语法上没有用。

答案 1 :(得分:1)

this

static关键字在{{1}}方法

中不可用

答案 2 :(得分:1)

因此,当您调用公共静态函数时,{this}关键字不会引用父类(DamnEclipse类)。静态上下文中不允许使用{this}关键字。这就是为什么当你返回新的DamnEclipse时它起作用的原因。它创建了一个对象。

相关问题