“公共类型<>必须在其自己的文件中定义” 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(); 
  }
}
我收到错误消息:
The public type StaticDemo must be defined in its own file第一行错误public class StaticDemo
{。为什么会发生,我该如何解决?请注意,我的项目名称为StaticDemoShow,程序包名称为staticshow,类名称如代码中所述。
-仅公开一个类或两个类均为默认类后,出现错误“选择不包含主类型”。现在我该怎么办?
回答:
如果.java文件包含顶级(非嵌套)public类,则其名称与该公共类相同。因此,如果您有类似的课程,public class
A{...}则需要将其放置在A.java文件中。因此, 。
如果允许有两个公共类,则可以说,除了公共A类文件之外,还将包含public class B{}它,这也将要求A.java文件中的文件 也
被命名为,B.java但是文件不能具有两个(或多个)名称(至少在所有系统上)可以运行哪个Java)。
因此,假设您的代码位于StaticDemoShow.java文件中,则有两个选择:
- 如果要在同一文件中包含其他类,请将它们设为非公开(缺少可见性修饰符将表示 默认/程序包私有的 可见性)
        class StaticDemo { // It can no 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();
        }
    }
- 将所有公共类移到它们自己的 - .java文件中。因此,在您的情况下,您需要将其分为两个文件:- StaticDemo.java - public class StaticDemo { // Note: same name as name of file- 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); - } - } 
- StaticDemoShow.java - public class StaticDemoShow {- public static void main() { - StaticDemo.show(); - } - } 
 
以上是 “公共类型<>必须在其自己的文件中定义” Eclipse中的错误 的全部内容, 来源链接: utcz.com/qa/426062.html








