This question already has an answer here:

I have written the following code:

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

I am getting the error message:

The public type StaticDemo must be defined in its own file

error in the very first line public class StaticDemo {. Why is it happening and how can I resolve it? Note that my project name is StaticDemoShow, package name is staticshow and class names are as given in the code.

EDIT- After making just one class public or both the classes default, I am getting the error "Selection does not contain a main type". Now what should I do?

asked Nov 6 '13 at 14:29
调试记录:The public type <<classname>> must be defined in its own file_其他
Mistu4u
1,31751948

marked as duplicate by HolgerDennis MengRaedwaldDavid LJarrod Roberson Nov 6 '13 at 22:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

 
   
Is your class file named StaticDemo? – Vaughan Hilts Nov 6 '13 at 14:30 
   
@VaughanHilts, No. My project name is "StaticDemoShow". – Mistu4u Nov 6 '13 at 14:34
2  
No need to downvote IMHO. Every beginner will stumble across this. @VaughanHilts It seems both are in the same file. – Axel Nov 6 '13 at 14:34
   
   
just in case you need to rightfully have mulitple types in one file, you may get here and look for another answer and motivation provided here: stackoverflow.com/questions/32012525/… – Andreas Dietrich Aug 14 '15 at 14:33 

8 Answers

We cant have two public classes in one file. The JVM cannot understand, in one file we must write one public class only.

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

}
 class StaticDemoShow {
    public static void main() {
        StaticDemo.show();
    }

}