+ 4
Why main method is to be public and static always?
3 odpowiedzi
+ 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();
}
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...
0
follow the first one ... bro