How to execute a main method from Interface

lookof2day 0 Tallied Votes 715 Views Share

Well any Java programmer knows that a Java Interface only allows declaration of methods. You cannot define the methods inside interfaces.

Yet if somebody like me wants you to define a method in interface and wants the program gets compiled and runs successfully, what would you do?

Well the answer is Inner Classes in Java. Through Inner classes, you can define a method in interfaces and run your programs.

Here's what you need to do:

public interface IMain{
        public class Main{
              public static void main(String [] args){
                   System.out.println("The main is defined inside an Interface". Don't believe me? Look at the source.. Geee..");
              }
        }
}

compile the program using javac.
run the program by typing java IMain$Main.
manix413 0 Newbie Poster

jjjjj

Allen Chen 0 Newbie Poster

Think about in any class?

Ezzaral 2,714 Posting Sage Team Colleague Featured Poster

Well, perhaps you could do that, but there is no reason at all that you should do that. If you want to provide method implementations along with an interface definition you should be using an abstract class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.