"公共类型<< classname >>必须在其自己的文件中定义"Eclipse中的错误

Mis*_*u4u 16 java eclipse

我写了以下代码:

package staticshow;


public class StaticDemo {
  static int a = 3;
  static int b = 4;

  static {
    System.out.println("Voila! Static block put into action");
  }

  static void show() {
    System.out.println("a= " + a);
    System.out.println("b= " + b);
  }
}

public class StaticDemoShow {
  public static void main() {
    StaticDemo.show(); 
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

The public type StaticDemo must be defined in its own file
Run Code Online (Sandbox Code Playgroud)

第一行中的错误public class StaticDemo {.为什么会这样,我该如何解决?请注意,我的项目名称是StaticDemoShow,包名称staticshow和类名称在代码中给出.

编辑 - 在只公开一个类或两个类默认后,​​我收到错误"选择不包含主类型".那我该怎么办?

Raj*_*dda 27

我们不能在一个文件中有两个公共类.JVM无法理解,在一个文件中我们只能编写一个公共类.

class StaticDemo {//it can ono longer public

    static int a = 3;
    static int b = 4;

    static {
        System.out.println("Voila! Static block put into action");
    }

    static void show() {
        System.out.println("a= " + a);
        System.out.println("b= " + b);
    }

}

public class StaticDemoShow { //only one top level public class in same .java file
    public static void main() {
        StaticDemo.show();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 来自C#,这种限制令人非常恼火 (5认同)
  • 任何有关为什么的见解? (2认同)

Pau*_*tha 11

不能在同一个文件中有两个公共类

   public class StaticDemo{
Run Code Online (Sandbox Code Playgroud)

改成

   class StaticDemo{
Run Code Online (Sandbox Code Playgroud)


Are*_*reo 5

Java规则:public一个文件中的一个类.