Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we have a main() in an interface and different implementations for main() in the classes that implement this interface?

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");
    }
}
like image 429
Galaxin Avatar asked Mar 14 '12 09:03

Galaxin


People also ask

Can an interface have main () method?

Apart from the interface as shown above, we can have main() method in an abstract class & enum as below.

Can multiple classes implement the same interface in Java?

A class can implement multiple interfaces and many classes can implement the same interface.

Can I implement more than one interface in a normal class?

Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

What happens when a class implements an interface?

A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.


2 Answers

With Java-8 you can have main method defined inside the interface, Below code will work in Java-8.

public interface TestInterfaces {
    public static void main(String[] a){    
        System.out.println("I am a static main method inside Inteface !!");
    }
}
like image 78
Nitin Dandriyal Avatar answered Oct 31 '22 02:10

Nitin Dandriyal


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.

like image 38
UmNyobe Avatar answered Oct 31 '22 01:10

UmNyobe