-4

I was trying to write a Java program with more than 1 public class and it gave me the following error:

Class [classname] is public,should be declared in a separate file named 
[classname].java

Can't seem to find a convincing answer as to why this is happening.

4

3 回答 3

3

You can not declare more than one public class in one .java file. Separate your classes to different .java files.

Class1.java

public class Class1 {

}

Class2.java

public class Class2 {

}

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

Similar questions:

于 2013-02-22T11:21:43.743 回答
2

类名与文件名相同。如果文件中有多个类,则会产生冲突,从而导致错误。所以每个类都应该在一个单独的文件中,文件名与类名相同。

于 2013-02-22T11:26:23.030 回答
2

每个公共类都必须在它自己的 .java 源文件中声明。

于 2013-02-22T11:22:21.303 回答