0

Can a .java file have multiple classes (including the main) and interfaces inside it? Or do I have to put them in different .java files?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

3 Answers3

6

You can have multiple classes and interfaces in the same file but the name of the file should be the class which is public.

You can't have more than one public class in a file.

When ever you compile this file, class files for each class will be generated.

Johny
  • 2,128
  • 3
  • 20
  • 33
1

You can have multiple top-level classes or interfaces inside a Java source file. However, if one of them is public, the file must be named after that class. Therefore you can only have one public class in a Java source file.

Example of a Java source file containing multiple classes and interfaces:

package somepackage;

// note that main classes do NOT need to be public, as some people are saying.
class MainClass {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

// multiple classes
class Class2 {
}

interface Interface1 {
}

// multiple interfaces
interface Interface2 {
}

You can also have inner classes/interfaces (even public ones), nested classes/interfaces (even public ones), and anonymous classes.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

You can have any number of classes in a java file . But the class with the main() method should be public.

So ,there can only be one public class per .java file, as public classes must have the same name as the source file. Still you can have any number of private class.

Also have a look at Java: Multiple class declarations in one file

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56