Can Java's main() method be declared final?

  • A+
Category:Languages

In Java, which declaration of the main() method is valid? We commonly use public static void main(String[] arr){}, but what I want to know is: can the main() method be declared final?

final public static void main(String[] arr) {     //... } 

 


Yes, you can mark main final.

While it is possible, it is not really meaningful. final methods can not be overriden. But static methods cant anyways, since they are not inherited when extending.


Hiding

However, it has an effect when actually hiding by introducing a method with the same name in an extending class. See Behaviour of final static method.

A contrived example to this:

public class A {     public static void main(String[] args) {         System.out.println("Hello from A");     } }  public class B extends A {     public static void main(String[] args) {         System.out.println("Hello from B");     } } 

Suppose you are calling those methods manually:

A.main(null);  // "Hello from A" B.main(null);  // "Hello from B" 

Note that Java also allows to call static methods from instances:

A a = new A(); a.main(null);  // "Hello from A"  B b = new B(); b.main(null);  // "Hello from B" 

But what if you reduce the view of a B object to an A object:

A bAsA = new B(); bAsA.main(null); // "Hello from A" 

And this might be surprising. Since, usually, it will take the method from the actual instance, which would be B. But that only applies when you are actually overriding methods, which is never the case with static methods.

Marking main as final will result in no subclass being able to hide your method anymore. That is, B will not be able to declare a method main anymore (with the same signature). The above code will then not compile.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: