Can we declare the main () method as final in Java?

Yes, we can declare the main () method as final in Java. The compiler does not throw any error

 final keyword in a method declaration to indicate that the method cannot be overridden by subclasses

If we are using inheritance and we need some methods not to overridden in subclasses then we need to make it final so that those methods can't be overridden by subclasses.

We can access final methods in the subclass but we can not override final methods

 

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

 

Output:

ParentClass method
ChildClass method

 


Subscribe For Daily Updates

Flutter Questions
Android Questions