我们可以在接口中使用main(),在实现此接口的类中使用main()的不同实现吗?

Gal*_*xin 9 java overriding program-entry-point

我知道main()可以在一个类中重载,编译器总是将一个String[] argsas作为参数作为执行开始的main方法.但是有可能宣布相同

main(String args[]) in an interface and implement it in different classes differently?
Run Code Online (Sandbox Code Playgroud)

例如,

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

UmN*_*obe 16

不,你不能,因为main必须是静态才能用作入口点,而Interfaces不允许使用static,直到Java 7.

psvm的,如果您正在工作,您可以在界面中运行Java 8.因为从Java 8开始的接口中允许使用静态方法.

但是,当然,你不能覆盖该main方法,因为它psvm是一个静态方法.

  • 然而,还有更多的答案.;) (2认同)

Nit*_*yal 11

使用Java-8,您可以在接口内定义main方法,下面的代码将在Java-8中使用.

public interface TestInterfaces {
    public static void main(String[] a){    
        System.out.println("I am a static main method inside Inteface !!");
    }
}
Run Code Online (Sandbox Code Playgroud)