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

此生再无相见时 提交于 2019-12-21 09:27:06

问题


Can anyone tell me the use of making main method as final in java.

while this is allowed in java

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



}

I dont see any use of making it final. anyways it is static so we can not override it.


回答1:


Adding final to a static method can actually 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 would prevent accidental hiding of A.main. In other words, adding final to A.main guarantees that B.main is not allowed, and that C.main therefore prints "A" as opposed to for instance "B".

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

Beside the above corner case, adding final to a static method doesn't make much difference, so I don't see a big point in adding a rule for disallowing it.

More information available here: Behaviour of final static method



来源:https://stackoverflow.com/questions/26042833/why-are-we-allowed-to-have-a-final-main-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!