0

I was asked whether,

public static void main(String[] args) {}

be overridden any no of times in same class ? can any one explain this

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Nani
  • 363
  • 2
  • 4
  • 8
  • @PradeepSimha Your link talks about overloading the main method, not overriding. – Alexis C. Dec 24 '13 at 15:53
  • This question makes very little sense and if it was an interview, it might be one of those in which they want to see the reaction. Method can't be overridden in the same class, static methods can't be overridden at all and there is very little sense in overriding the `main()` in the same class. – Andrey Chaschev Dec 24 '13 at 15:56
  • @ZouZou, sorry I think I got confuse – Pradeep Simha Dec 24 '13 at 16:01

5 Answers5

2

You ask:

Can Main method be overridden any number of times?

No, it can't be overridden even once due to the plain fact that you can't override static methods.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

No, you cannot override any method within the same class. If you try to override it in another class, that is not going to work, since you cannot override static methods (because that makes no sense if you think about it in the context of OOP).

Overloading methods can be done. You can overload a method called main, but that method will never be the entry point of your application, since it has not the required arguments to launch. The only three correct ways to define a main methods are:

public static void main(String args[])
public static void main(String[] args)
public static void main(String ...args)

Note that this is neither overloading or overriding: these signatures are equally treated.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

yes, we can 'overload' main method in java even in the same class you can something like

public static void main(int arr[])

or

public static void main(float f)

but when you execute your application, JVM will search for main method with String[] args i.e.

public static void main(String[] args)
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
Gagan93
  • 1,826
  • 2
  • 25
  • 38
0

A class can only contain a single method with that name and signature.

It can have other methods with the same name and different argument types. However, those methods will have no special significance as far as starting the program is concerned.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Yes, surely you can overload main method in Java. Keep in mind, when you run/execute the program, it doesn't execute overloaded main function automatically. You still have to call the overloaded main method from the Main method.

thestar
  • 4,959
  • 2
  • 28
  • 22