-2

Java class's main method is implemented as:

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

Why wasn't it implemented as public static final void? We can use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses, which seems like a desirable property for a class main method?

Perhaps it is because "because a static method cannot be overridden", and so the final keyword would be redundant, but I am curious if there are other reasons to be aware of.

zthomas.nc
  • 3,689
  • 8
  • 35
  • 49
  • What would `final` mean for a method, rather than a field? Java isn't Javascript, you don't just get to assign a new method signature and body to an existing class method name at runtime (you need to jump through _a lot_ of hoops if you want to break expectations that badly). As for preventing overrides in subclasses: why would that be necessary? Only the main method of the class that Java "starts the run on" gets invoked. You can have a million subclasses each with their own main and they would have zero effect? – Mike 'Pomax' Kamermans Oct 11 '21 at 17:58
  • 2
    What other reason is necessary than that `static` is essentially already `final`? – chrylis -cautiouslyoptimistic- Oct 11 '21 at 18:02
  • What would Java gain if it would require you to write the main method as a `public static final void` method? Note that although Java doesn't require that you write your main methods as `public static final void main(..)` you can still to write them that way if you desire. – Thomas Kläger Oct 11 '21 at 19:08

1 Answers1

2

I believe you've answered your own question. The final keyword prevents a method from being overridden. Since static methods cannot be overridden, it would be redundant to make the main method final.

Janos Vinceller
  • 1,208
  • 11
  • 25
pietnam
  • 53
  • 6
  • It sounds like these keywords operate differently on variables, since `private static final` is commonly used to declare constants in Java? – zthomas.nc Oct 11 '21 at 18:06
  • Static variables can change their values. The `public static final` variation means, these values are like constants, `final` prevent changing them. This is different from declaring methods `final`. – Janos Vinceller Oct 11 '21 at 18:09
  • The `final` keyword works differently on variables. The value of a `final` variable cannot be changed. – pietnam Oct 11 '21 at 18:14