-
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 program and the
name of the public class must match 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.
class A{
}
class B{
}
class C{
}
class D{
}
save program name any classname.java
case 2-: if class B is public then name of program should be B.java other wise
we will get 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-:if class B and C declared as public and name of 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
class A{
}
public class B{
}
public class C{
}
class D{
}
Note-:
- whenever compiling a java program for every class present in the program a separate (.class) file will be generated.
- we can compile java program(java source file) but we can run a java dot class (.class)
- whenever exciting a java class the corresponding class main method will be executed.
- if the class doesn't contain the main method then we will get a run time exception saying noSuchMethodError: main
- if the crossponding(.class file) is not available then we will get a run time exception saying 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 we have to keep the same as the class name. the main advantage of this approach is readability and maintainability of the code will be improved.
Example-:
class A{
public static void main(String... args){
System.out.print("hello");
}
}
class B{
public static void main(String... args){
System.out.print("hello");
}
}
class C{
public static void main(String... args){
System.out.print("hello");
}
}
class D{
}
java A
output-: hello
java B
output-: Hi
java C
output -: Bey
java D
Run time Error-:NoSuchMethodError : main
java Test
Run time Error-:NoClassDefFoundError :Test