1

this is how we can override main function in java....

public class animaltest 
{
    public static void main(String[] args)  
    {
        horse h = new horse();
        h.eat();
    }
}

public class inheritmain extends animaltest 
{
    public static void main(String[] args)  
    {
        System.out.print("main overrided");
    }
}

but what is the benefit of overriding main??

3 Answers3

7

static methods do not override: they are shadowed. There are two different independent static methods in that case, namely animaltest.main and inheritmain.main. (See Can we override static method in Java?)

The "advantage" -- if any ;-) -- is that the program can be started/launched from either class as both classes implement the main method:

The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.

Happy coding.

Community
  • 1
  • 1
2

Overriding is not for STATIC functions, overriding is only for member functions which are not static.

In this case, No POLYMORPHIC will be observed.

Zohaib
  • 7,026
  • 3
  • 26
  • 35
0

I dont think you can override main in Java because you don't inherit main from any class in the first place. Hence there is nothing to be overriden.

Jeune
  • 3,498
  • 5
  • 43
  • 54