Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - "The public type <<classname>> must be defined in its own file" error in Eclipse


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If .java file contains top level (not nested) public class, it has to have the same name as that public class. So if you have class like public class A{...} it needs to be placed in A.java file. Because of that we can't have two public classes in one .java file.

If having two public classes would be allowed then, and lets say aside from public A class file would also contain public class B{} it would require from A.java file to be also named as B.java but files can't have two (or more) names (at least in all systems on which Java can be run).

So assuming your code is placed in StaticDemoShow.java file you have two options:

  1. If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility)

     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();
         }
     }
    
  2. Move all public classes to their own .java files. So in your case you would need to split it into two files:

    • 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();
            }
        }
      

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...