I have a java file containing more than one class, out of which one is public. If main method is inside a non-public class. I can\'t run that java file. Why is that? and the
Have a look at this code:
Super.java
public class Super{ }
class Sub{
public static void main(String[] s){
System.out.println("Hello");
}
}
In order to print Hello
you can compile and run the program as:
How this works?
The compiler generates separate .class
file for every class in your program. So, instead of calling the main()
of non-public class from the public class's main()
you can print the output as shown above.
Note: As the convention says, you must put a public class
in separate file
. And do not put more than one class in a single file (except if they are inner class) because if you would like to import them or use them with other classes then it will cause problem.