英文:
',' 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论