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

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

王林
Release: 2023-08-26 23:49:03
forward
1324 people have browsed it

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));
   }
}
Copy after login

Output

BaseClass method
DerivedClass method
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template