Sachin Sabbarwal
Sachin Sabbarwal

Reputation: 143

What purpose does "overriding" main serve in Java?

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??

Upvotes: 1

Views: 366

Answers (3)

user166390
user166390

Reputation:

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.

Upvotes: 7

Jeune
Jeune

Reputation: 3548

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.

Upvotes: 0

Zohaib
Zohaib

Reputation: 7116

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

In this case, No POLYMORPHIC will be observed.

Upvotes: 2

Related Questions