简体   繁体   中英

how do I get rid of the following error in Eclipse?

The error I get is exactly the error specified in:

http://java.syntaxerrors.info/index.php?title=Own_file

(class must be defined in its own file.)

but they don't give a solution there how to solve it, other than just having a file per public class.

Thank you, eclipse, for making me do this, but this is not mandatory in Java. Is there a way to get rid of this error?

Yes, it is mandatory in Java. Each public class has to be in a separate file named exactly the same way as the class.

See this question about it . The Java language specification writes that this is not 100% mandatory for compilers, but they usually do that. And since it is a good thing, and is noted in the spec, all compilers do it.

When packages are stored in a file system (§7.2.1), 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 you want to have multiple classes in the same file, that's a different story. You can do it in two ways:

  • declare them as package-private classes with class Foo after the body of the main class. You can have any number of non-public classes in the same file
  • declare them as static inner classes: public static class InnerFoo inside the main class body. That way they will be visible to other classes by FooClass.InnerFoo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM