can we have a main() in an interface and different

2019-04-26 03:41发布

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

11条回答
乱世女痞
2楼-- · 2019-04-26 04:34

You can write static main method in Interface in java 8 but you can't override it as it's a static one.

查看更多
别忘想泡老子
3楼-- · 2019-04-26 04:35

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.

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.

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

查看更多
Ridiculous、
4楼-- · 2019-04-26 04:35

you declared a main(String[] args) as static in Testclass1,but in interface "test" it is non-static and interface not allow main(String[] args) as static .even if you override main(String[] args) in Testcalss1 as non-static it's not allowed, because main(String args) is already defined in Testclass1.so you cannot declare main(String[] args) in interface.And u done a one more mistaken is initializing the interface test as t.You cannot do that.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-04-26 04:37

There are two answers for your question.

  1. First of all, you can't have static methods in an Interface
  2. Yes you can overload main() method, but when you launch your class, only the public static void main(String args[]){} method will be treated as an entry point.

For example

public class Test {
    public static void main(String[] args) {
        System.out.println("entry point)");
    }

    public static void main(String arg1) {
        System.out.println("overload2");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("overload3");
    }
}

When you launch the above class, the out will be "entry point"

查看更多
我想做一个坏孩纸
6楼-- · 2019-04-26 04:40

main() is static.so, we cant override static methods.Interfaces allows abstract methods methods & they will be implemented in subclasses.So, abstract methods never be static.finally I concluded that main() is not possible to execute in interfaces.

查看更多
登录 后发表回答