I expected the following code to have compiler issues but surprisingly it did not.
class p {
static int a = 10;
public static void main(String...args) {
System.out.println(a);
}
}
class child extends p {
public static void main(String[] args) {
System.out.println(p.a+10);
}
}
Can anyone tell me:
a) Why the compiler is not complaining about multiple main()
methods?
b) When I execute the above program from the command line I can see that only the class p's main()
method is getting executed? What is the rationale behind that?
The main
method is just like any other method in Java, in that you can have the same name and signature on multiple classes.
It is special because to run anything in Java, you must specify the class containing the correct main
method to run.
You must have specified class p
to run:
$ java p
10
You could also specify class child
to run:
$ java child
20
Compiling the child
class gives you a warning:
Child.java:3: warning: main(java.lang.String[]) in Child cannot override main(java.lang.String...) in P; overriding method is missing '...'
But we already know that static
methods aren't inherited. It's okay, we're not trying to inherit here anyway.
Also, String...
is resolved to a String[]
anyway, so the signatures are equivalent.
a) Why would the compiler complain about it? The methods are defined in 2 different classes, which is perfectly legal in Java (although probably not advisable to have the same field names common within the super and sub class).
b) It depends on which class you are running; you must be running the p
class.
main method acts as an entry point of your program. By declaring multiple main method in multiple class, you only declared multiple entry point and Java has no problem whatsoever with that.
Afterall when you run your program via command line you have to specify which class should be used as an entry point. Assuming your source file is called p.java
, running your program with:
java p
Will cause p's main method to be invoked, whereas if you run your program with:
java child
The main method of child
class will run instead of p
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.