Java “方法 main 不能声明为静态;静态方法只能在静态或顶级类型中声明”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22787063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"The method main cannot be declared static; static methods can only be declared in a static or top level type"
提问by Lotix
class Perkusja {
boolean talerze = true;
boolean beben = true;
void zagrajNaBebnie() {
System.out.println("bam, bam, baaaa-am-am");
}
void zagrajNaTalerzach() {
System.out.println("brzd?k, brzbrzrzd??k");
}
class PerkusjaTester {
public static void main(String[] args) {
Perkusja p = new Perkusja();
}
}
}
Hello! I'm new to stackoverflow so please forgive me my atrocious editing.
你好!我是 stackoverflow 的新手,所以请原谅我的粗暴编辑。
I'm new to Java and i can't figure out where exactly the issue lies and what's the problem.
I get the following error on the line
public static void main(String[]args)
:
我是 Java 新手,我无法弄清楚问题究竟出在哪里以及问题出在哪里。我在线上收到以下错误
public static void main(String[]args)
:
The method main cannot be declared static; static methods can only be declared in a static or top level type
方法 main 不能声明为静态;静态方法只能在静态或顶级类型中声明
I'm using eclipse and i'm doing some simple java exercises. I googled the problem but the answers are usually related to much more complex pieces of code.
我正在使用 eclipse 并且我正在做一些简单的 java 练习。我用谷歌搜索了这个问题,但答案通常与更复杂的代码片段有关。
How do i fix it and what's the cause of the following error? I'd be grateful for an explanation on this particular example.
我该如何修复它以及出现以下错误的原因是什么?我将不胜感激对此特定示例的解释。
Cheers!
干杯!
采纳答案by Arnaud Denoyelle
You are declaring your main method in PerkusjaTester
which is an inner class of Perkusja
. That is forbidden.
您正在声明您的主要方法,PerkusjaTester
其中是Perkusja
. 那是被禁止的。
You should declare your test class outside of class Perkusja
你应该在课堂之外声明你的测试类 Perkusja
Note : PerkusjaTester
is an inner class, not a static nested class. That is why PerkusjaTester
is not a static type. As mentionned by Jon Skeet, you could also add the keyword static
on class PerkusjaTester
.
注意:PerkusjaTester
是内部类,不是静态嵌套类。这就是为什么PerkusjaTester
不是静态类型的原因。正如 Jon Skeet 所提到的,您还可以static
在 class 上添加关键字PerkusjaTester
。
回答by Bathsheba
This code cannot work since, conceptually, an instance of an Perkusja
would have to be declared in advance of main
being called.
此代码无法工作,因为从概念上讲,Perkusja
必须在main
调用之前声明an 的实例。
This is because the inner class PerkusjaTester
is notmarked as static.
这是因为内部类PerkusjaTester
是没有标记为静态的。
The best fix for you is to write static class PerkusjaTester {
.
对您来说最好的解决方法是编写static class PerkusjaTester {
.
Then main
is accessible.
然后main
是可以访问的。