Do you know Java: Entry Point in Interface or Enum


All Java applications start with a class and an entry point in it. We can change the class type to others.

All Java applications start at one common point. That is a class which has at least one static method, called main as an entry point of the app. This method is called by JRE after the class is loaded when we execute java command with the appropriate name of the class.

Java has more than just primitive types and class types. There are interfaces, enums, different kind of reference types. Is it possible to use other types in the place of class to make the entry point available for JRE for calling it?

The usual way

A well-known Hello World looks like this:

class Main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

After executing it, Hello World! is printed to the standard output.

Interface

We have more choice than just a class to place code in it. Thank to Java 8 and onwards, interface is available to place static method in it.

interface Main {
    public static void main(String[] args) {
        System.out.println("Hello Interface!");
    }
}

JRE calls the entry point as Main.main(...) without caring about the kind of Main. After the binary got executed, Hello Interface! pops up on the std out.

Enum

enum is also a class type, with some extras. All types that are defined as enum implicitly inhereted from Enum special class.

enum Main {
    ;
    public static void main(String[] args) {
        System.out.println("Hello Enum!");
    }
}

enum requires to have a semicolon (;) at least if we have methods in the enum. It prints Hello Enum! to std out after we executed the java Main command.

Compare them

The most common type where we place the entry point is definitely class type. Though class is very tempting to put a constructor and then instanciate the class inside the entry point. Grrhh! Do not do that! Keep it as clean as possible! Let Main be as a container of main method and that’s it!

Interface does not allow us to define a constructor inside and instanciate it in main method. Obviously, it could be as an anonymous inner class, but also ugly. Hope, that is ugly enough for developers to not to do that. Definitely that is a code smell.

Enum brings the need to introduce at least one object with makes the code botched. Totally superfluous and misleading, hence enum is also not the choosen one.

Though I would go for interface, since it seems as the safest and less tempting for further code mish-mashing. On the other side this approach can be very misleading for those developers who are new in the world of Java 8.

Code can be found: https://github.com/torokmark/do-you-know-java