Class is public, should be declared in a file named .java

36.5k Views Asked by At

I'm having this problem which I'm not sure why it's caused.

"class Account is public, should be declared in a file named Account.java"

I have 5 classes in my program, all in the same file and all are public:

  • Class called Main which includes the main method
  • Class called Account is abstract
  • 3 classes Account1, Account2, Account3 which extend the abstract class

I named my file Main.java, and it's giving me this error. Then I named my file Account.java, and I got the same error again.

What should I do?

3

There are 3 best solutions below

0
On
  1. There can be only one public class per source code file.
  2. If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java.

You should split up your file into 5 files so that you only have one class per file.

0
On

This shouldn't be realy hard to solve, because you already provided the answere. You can't have 2 separated public classes in a single java file. So as suggested: create a file Account.java for your account class. If you keep this class in the same package, there is nothing else you have to do.

0
On

I just run into your situation at some time, I just check the website on oracle

the obvious said that in the .java file, all your 5 classes is all top-level, so

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

so you can, of course, place your classes to another .java files, or u can just delete your prefix or modifier of your class, and your code will run, but the class can only accessed within this package!