Why are we allowed to have the last main method in java?

Can someone tell me how to use the main method as final in java.

while this is allowed in java

public static final void main(String[] args) { } 

I see no way to make it final. in any case, it is static, so we cannot redefine it.

+6
source share
1 answer

Adding final to a static method can really make a difference. Consider the following code:

 class A { public static void main(String[] args) { System.out.println("A"); } } class B extends A { public static void main(String[] args) { System.out.println("B"); } } class C extends B { } public class Test { public static void main(String[] args) { C.main(args); // Will invoke B.main } } 

Adding final to A.main prevent accidentally hiding A.main . In other words, adding final to A.main ensures that B.main not allowed, and that C.main therefore prints "A" as opposed to, for example, "B" .

Why are we allowed to have the final main method in java?

Besides the aforementioned corner case, adding final to the static method doesn't really matter, so I don't see a big point in adding a rule to ban it.

Further information is available here: Final Static Method Behavior

+10
source

Source: https://habr.com/ru/post/975841/


All Articles