我们可以在接口中具有main(),并在实现此接口的类中具有main()的不同实现吗? [英] can we have a main() in an interface and different implementations for main() in the classes that implement this interface?

查看:90
本文介绍了我们可以在接口中具有main(),并在实现此接口的类中具有main()的不同实现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道main()可以在类中重载,编译器始终以String[] args作为参数,将其作为执行开始的主要方法.但是是否可以声明相同的

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?

例如,

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");
    }
}

推荐答案

不能,因为main必须是静态的才能用作入口点,并且接口不允许使用静态,直到Java 7.

No you cannot, because main has to be static in order to be used as an entry point, and Interfaces dont allow the use of static, until Java 7.

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

Yes you can run a psvm in an interface, if you're working in Java 8. Because static methods are allowed in an interface starting from Java 8.

但是,当然,您不能覆盖main方法,因为psvm是静态方法.

But of course, you cannot override the main method, since psvm is a static method.

这篇关于我们可以在接口中具有main(),并在实现此接口的类中具有main()的不同实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆