Declarations and Access Modifiers in Java

A Java program can contain any number of classes but at most one class can be declared as public. If there is public class then name of the program and name of the public class must be matched, other wise we will get compile time error.

Case 1

If there is no public class then we can use any name and there are no restrictions.

Case 2

If Class B is public then name of the program should be B.JAVA, otherwise we will get compile time error saying Class B is public, should be declared in a file named B.Java.

Case 3

If class B and C declared as public and name of the program is B.JAVA then we will get compile time error saying Class C is public, should be declared in a file named C.JAVA.