Can We Have Multiple Classes in Same Java File?

Yes, we can have multiple classes in same java file. But, there is one restriction over here, which is that you can have as many classes in one file but only one public class is allowed. If we try to declare 2 classes as public in the same file, the code will not compile.

The reason being is you need to name the file with the name of the class which is declared as public and we cannot have the same file with different names, and also that public class should be containing the main method as the compiler will check for the main method first. So, there is no chance to have two public classes in one file.

If we want to access the methods, instances of the other classes we can just make their respective objects in the public file and simply access them.

Let’s consider two examples:

Example 1:

public class test{
	public static void main(String...s){
		System.out.println("Hello Guys");
	}
}

class test1{}

class test2{}

So if we save the file with test.java it will compile successfully, but if we try to change and save the file with test1.java the compilation will fail.

Can We Have Multiple Classes in Same Java File?

Example 2:

public class test{
	public static void main(String...s){
		System.out.println("Hello Guys");
	}
}

public class test1{}

class test2{}

So if you save it with either name test1 or test2 it will eventually lead to compilation fails.

So, there should be one public class in one file, but here is a point to note:- “public class can have inner classes in it”. Also, if there is no public class in a java file, it is not advisable to do that as it will affect the readability of the code.

1 thought on “Can We Have Multiple Classes in Same Java File?”

Leave a Comment

Your email address will not be published. Required fields are marked *