Java Source File Structure
A Java program can contain any number of classes, but at most one class can be declared as public. If there is a public class, the name of the source file (program) and the name of the public class must match; otherwise, you will get a compile-time error.
Case 1: No Public Class
If there is no public class, you can save the program with any name (e.g., anyclassname.java), and there are no restrictions.
class A {
}
class B {
}
class C {
}
class D {
}
Case 2: One Public Class
If class B is declared as public, the name of the program should be B.java; otherwise, you will get a compile-time error saying "class B is public, should be declared in a file named B.java".
class A {
}
public class B {
}
class C {
}
class D {
}
Case 3: Multiple Public Classes
If classes B and C are declared as public and the name of the program is B.java, you will get a compile-time error saying "class C is public, should be declared in a file named C.java".
class A {
}
public class B {
}
public class C {
}
class D {
}
Notes
- Whenever compiling a Java program, a separate
.classfile will be generated for every class present in the program. - You can compile a Java source file (.java), but you can only run a
.classfile. - When executing a Java class, the corresponding class's
mainmethod will be executed. - If the class doesn't contain a
mainmethod, you will get a runtime exception:NoSuchMethodError: main. - If the corresponding
.classfile is not available, you will get a runtime exception:NoClassDefFoundError. - It is not recommended to declare multiple classes in a single source file. It is highly recommended to declare only one class per source file, and the name of the program should match the class name. The main advantage of this approach is improved readability and maintainability of the code.
Example
Suppose you have the following code in a file named A.java (note: this violates best practices by having multiple classes in one file, but it's used here for illustration):
class A {
public static void main(String... args) {
System.out.print("hello");
}
}
class B {
public static void main(String... args) {
System.out.print("Hi");
}
}
class C {
public static void main(String... args) {
System.out.print("Bey");
}
}
class D {
}
Command: java A
Output: hello
Command: java B
Output: Hi
Command: java C
Output: Bey
Command: java D
Runtime Error: NoSuchMethodError: main
Command: java Test
Runtime Error: NoClassDefFoundError: Test