Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (6.5k points)
I'm confused as to when we can use the 'final' keyword when it concerns a method.

1 Answer

0 votes
by (11.3k points)

Yes, we can make the 'main' method 'final' in the following manner:

class A{

public static final void main(String arg[]) {

System.out.println("A");

}}

Keep in mind that 'final' methods cannot be overridden by inheritor classes. For example, if a 'class B' extends 'class A' in the following manner:

class B extends A

     public static void main(String arg[]){

System.out.println("B");

}}

And a class C inherits class B in the following way:

class C extends B{

public static void main(String arg[]){

C.main(args) //to call for B's main method

}}

If class C is executed, when 'c.main' is called, it redirects to B's main method. Again, keep in mind that B cannot use its own main method as it would be overriding its parent class, A's main method. So, by default, since A's main method is 'final' and cannot be overridden, A's main method is called instead. 

Output:

A

Browse Categories

...