dcsimg
Overloading Static main method
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Howard_Roark
Posted On:   Wednesday, July 17, 2002 11:45 PM

How many main methods can we have in same class and can we overload, override static main method of a class?

Re: Overloading Static main method

Posted By:   Animesh_Srivastava  
Posted On:   Thursday, July 18, 2002 01:05 PM


The first part first
>>How many main methods can we have in same class


Well, we can have more than one "main" method. All we need to do is override, which means simply another method with same name "main" but a different signature. For ex, the following code will have no compile-time or run-time errors -


public class OverRideExample
{
public static void main (String[] args)
{
System.out.println("static main method");
OverRideExample a=new OverRideExample();
a.main();
}

public void main () //the overridden "main" method
{
System.out.println("overridden main method");
}
}


So essentially, in concept it is possible to override main method. Now to the second part of your question -



>> and can we overload, override static main method of a class?



Of course we can!! Just change the signature (either by changing the number or the type of arguments to the method). For ex, you could try out this -


public class OverRideExample
{
public static void main (String[] args)
{
System.out.println("static main");
main(4);
}

public static void main (int i) //overridden
{
System.out.println("overridden called, val="+i);
}
}


So again, in concept (and in practical) it is possible to override static main method. Though I am not sure in what (mysterious?) situations will you find this advantageous and would actually want to do such overriding ;)



Hope that helps!

Animesh.

Re: Overloading Static main method

Posted By:   Axel_Richter  
Posted On:   Thursday, July 18, 2002 01:08 AM

One, and only one, static void main() must give it only in such classes, which work directly with the JVM (the Main classes evenly). A class can have however several constructors. See:

http://java.sun.com/docs/books/tutorial/java/javaOO/classes.html
About | Sitemap | Contact