0

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?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
kloop
  • 4,537
  • 13
  • 42
  • 66
  • Are you sure about " but this is not mandatory in Java"? Even javac complains, if the name of the class isn't the same as the file name. – dunni Nov 13 '11 at 22:40

1 Answers1

4

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
Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • this is a silly restriction. I have many classes which inherit from the same class, all very short classes which have a very specific role. I see no reason why not to condense them all in the same source file. I am also pretty sure I used to do that in other cases, but I haven't been using java for a while. maybe it is now enforced in newer versions of Java. – kloop Nov 13 '11 at 22:52
  • it is not a silly restriction at all. You have multiple options for 'condensing' them, see my update – Bozho Nov 13 '11 at 22:53
  • @kloop If you have many subclasses that are very small, you can declare them as `public static class SubClass extends YourClass {}` *inside* the class declaration of `YourClass`. – Strelok Nov 13 '11 at 22:59
  • I think "private" is not the correct designation for a class without access modifier, shouldn't it be "default access" (or "package private")? Private classes are only allowed as member classes, not as top level classes. – user85421 Nov 13 '11 at 23:18