Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...