I know that main() can be overloaded in a class with the compiler always taking the one with String[] args
as arguments as the main method from where the execution starts. But is it possible to declare the same
main(String args[]) in an interface and implement it in different classes differently?
For example,
package test;
interface test
{
public void main(String args[]);
public void display();
}
package test;
class Testclass1 implements test
{
public void display()
{
System.out.println("hello");
}
public static void main(String[] args)
{
test t;
t.display();
}
}
package temp;
import test.*;
abstract class Testclass2 implements test
{
public static void main(String args[])
{
System.out.println("TESTING");
}
}
Answer : Yes, we can provide different implementation of main() declared in an interface and classes implementing that interface by overriding method and can overload static main method if defined in an interface.
Some more information regarding interface changes in Java 8.
Prior to Java 8, it was not possible to DEFINE methods inside interface.
But there are changes made to Java 8 with respect to interface where one can DEFINE default and static method inside an interface. Hence below code will work fine without any issue.
For information regarding this features, please refer below link: http://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method
I think you are missing something. Static methods (like the main method in
Testclass1
andTestclass2
) cannot override subclass methods.I am not sure But You can have multiple main methods in multiple classes (not the same class). We start the program with the name of the class whose main method we want to run. So after that JVM will look for main method in that class only. So there should not be any problem.
I am not sure so please let me know if I am wrong.
this is a compiler error. you cant override a non static interface a static method
With Java-8 you can have main method defined inside the interface, Below code will work in Java-8.
You can create you own startup mechanism, but I am not sure why you would want to.
BTW: You don't have to have a main() method, e.g.
compiles and runs without error.