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

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?

This question is related to java eclipse

The answer is


Cant have two public classes in same file

   public class StaticDemo{

Change to

   class StaticDemo{

I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.


error in the very first line public class StaticDemo {

Any Class A which has access modifier as public must have a separate source file as A.java or A.jav. This is specified in JLS 7.6 section:

If and only if packages are stored in a file system (ยง7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.

  • The type is declared public (and therefore is potentially accessible from code in other packages).

However, you may have to remove public access modifier from the Class declaration StaticDemo. Then as StaticDemo class will have no modifier it will become package-private, That is, it will be visible only within its own package.

Check out Controlling Access to Members of a Class


Java rule : One public class in one file.


You can have only one public class in a file else you will get the error what you are getting now and name of file must be the name of public class


You can't use 2 public class instances, you need to use one. Try using class (name) instead of public class (name)


Save this class in the file StaticDemo.java. Also you cant have more than one public classes in one file.