‘,” 预期,而不是在JAVA中的引用声明中使用 ‘;'”

huangapple go评论73阅读模式
英文:

',' expected instead of ';' on Reference Declaration in JAVA

问题

这是类错误出现在 `flyBehavir` 声明上就在分号上面

```java
package simUduck;

public class duck {
    void display(){

    }
    Fly flyBehaviour; // 这里
    flyBehaviour = new Fly(); // 这里
}

这是 Fly 类:

package simUduck;

public class Fly {
    void fly(){
        
    }
}

我实际上不想在 duck 类中初始化它,我只想在那里引用它,子类会初始化它。任何帮助将不胜感激。

以下语句不会产生错误

Fly flybehavior = new Fly();


<details>
<summary>英文:</summary>


*Here is the class and the error is on `flyBehavir` declaration, right on the semicolon*
```java
package simUduck;

public class duck {
    void display(){

    }
    Fly flyBehaviour;
    flyBehaviour = new Fly();
}

Here is the Fly class

package simUduck;

public class Fly {
    void fly(){
        
    }
}

I don't actually want a initialization in duck class, I just want a reference there and the child classes will initialize it. Any help would be appreciated.

The following statement doesn't give any error

Fly flybehavior = new Fly();

答案1

得分: 3

flyBehaviour = new Fly(); 是一个位于方法外部的语句。这是不允许的。每个语句必须位于方法、构造函数或初始化块内部。

因此,要么将其重写为初始化块(正如您在最后一行中所示),要么将其放入构造函数中:

public Duck() {
  flyBehaviour = new Fly();
}

(还要注意,我将 Duck 的首字母大写,因为按照惯例在 Java 中所有类名都应该大写)。

英文:

flyBehaviour = new Fly(); is a statement outside of a method. That is not allowed. Each statement must be inside a method, constructor or initializer block.

So either rewrite it as an initializer (as you showed in your last line) or put it into a constructor:

public Duck() {
  flyBehaviour = new Fly();
}

(Also note, that I capitalized Duck, because by convention all classes should be upper-case in Java).

huangapple
  • 本文由 发表于 2020年10月6日 15:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64221059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定