Home >Java >javaTutorial >In Java, can we declare main() method as final?

In Java, can we declare main() method as final?

王林
王林forward
2023-08-26 23:49:031328browse

In Java, can we declare main() method as final?

Yes, we can declare the main() method as final in Java. The compiler won't throw any errors.

  • If we declare any method as final by placing final keyword, then that method will become Final method .
  • The main purpose of final methods in Java is that they cannot be overridden.
  • We cannot override final methods in subclasses.
  • If we use inheritance and need some methods not to be overridden in subclasses, then we need to make them final so that these methods cannot be overridden by subclasses.
  • We can access the ffinal method in the subclass, but we cannot override the final method.

Example

class BaseClass {
   public final void show(Object o) {
      System.out.println("BaseClass method");
   }
}
class DerivedClass extends BaseClass {
   public void show(Integer i) {
      System.out.println("DerivedClass method");
   }
}
public class Test {
   public static final void main(String[] args) { // declaring main () method with final keyword.
      BaseClass b = new BaseClass();
      DerivedClass d = new DerivedClass();
      b.show(new Integer(0));
      d.show(new Integer(0));
   }
}

Output

BaseClass method
DerivedClass method

The above is the detailed content of In Java, can we declare main() method as final?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete