Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main method inside interface (java-8) [duplicate]

As java-8 allows static methods inside interface, I decided to check, will such simple compiled program successfully run:

public interface Test {
    static void main(String[] args) {
        System.out.println("I'm ok!");
    }
}

Surprisingly (for me) it runs perfectly.

What I am confusing about, is that in JVM specification terms class and interface have different semantics and usage. In this context I'm worry about is this behaviour is really according to JVMS or not? Because in fact JVMS Ch. 5.2. talks about class, not class or interface:

The Java Virtual Machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java Virtual Machine then links the initial class, initializes it, and invokes the public class method void main(String[]).

UPD:

I know, that interface itself is a class. But I'm talking about JVM, where often class and interface have different semantics. For example

The run-time constant pool for a class or interface is constructed when the class or interface is created (§5.3) by the Java Virtual Machine.

like image 787
Andremoniy Avatar asked Jul 17 '26 07:07

Andremoniy


1 Answers

The JVM spec is a bit lax in its wording here. If you refer to the referenced section 5.3.1, it says:

The following steps are used to load and thereby create the nonarray class or interface C denoted by N using the bootstrap class loader.

The point is that the same process is followed regardless of whether C is a class or interface.

The Java Language Specification is equally inconsistent in describing the virtual machine startup, at one point using "class" and at another using "class or interface".

In any event, having a main method as part of an interface should work perfectly well.

like image 51
Ted Hopp Avatar answered Jul 19 '26 22:07

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!