+ 4

Why main method is to be public and static always?

3rd Aug 2016, 1:19 PM
Rohan Gupta
3 Antworten
+ 6
If you have a program and you want your program to be run by JVM. Then you need a class that contain main method. Because JVM will start run your program from main. For example you have main in class A. JVM will call your programe via class A like. A.main(args); If main is not public, main method cannot be called, your program cannot be run. If main is not static, JVM need to create an instance for class A. e.g. A a = new A(); a.main(); But sometime your class may have constructor with parameter like A(int x){}. Then how JVM know what value of x when create new object A. e.g. int x = ? A a = new A(x); It would be better if let program A create constructor by itself inside main method. e.g. public static void main(String args[]){ int x = args[0]; A a = new A(x); a.doSomething(); }
3rd Aug 2016, 3:29 PM
WPimpong
WPimpong - avatar
0
It is static and public in order to use it everytime we need and everytime is needed to call methods in it so it should be accessible everywhere...
5th Aug 2016, 11:09 AM
Mohammad
0
follow the first one ... bro
15th Dec 2016, 1:28 PM
Prashant Malviya
Prashant Malviya - avatar