We Don't know JAVA #EP8 
Interface static method

Photo by Andrew Neel on Unsplash

We Don't know JAVA #EP8 Interface static method

Guess The Answer First

interface Main{
    public static void main(String ... args){
    System.out.println("EP8");
    }
}

Options

1. EP8 will be printed

2. Nothing will be printed

3. Compile Time Error

4. Runtime Error

Answer: EP8 will be printed

If you knew the answer it's good but if you don't let's fix that.

Point no 1: How the normal class main method executes.

FileName: Main.java

class Main{
    public static void main(String ... args){
    System.out.println("EP8");
    }
}

In the above code after compiling the Main.java file will be converted into Main.class file and then it will be loaded by JVM and since the class file name is Main.class JVM will search for the static main method with String [] argument in Main.class and JVM will execute it.

Flow Diagram

classflowchart (Small).png

Interface Static Method (Java 1.8 feature)

Well we all know that interface is a replacement for abstract class and it can only contain abstract method. Ex:

interface  Main{
public void demo(); 
public int add(int a,int b);
}

But in Java 1.8 features they introduced static method in interface.

Example 1:

interface Main{
public static void demo(){
      //Normal code
    }
}

Note: Main method is nothing but a simple static method .

Example 2:

interface Main{
public static void main(String [] args){
      //Normal code
    }
}

Point no 2: How the interface main method executes.

FileName: Main.java

interface Main{
    public static void main(String ... args){
    System.out.println("EP8");
    }
}

Conclusion: Well No difference it will be execute as same as class.

In the above code after compiling the Main.java file will be converted into Main.class file and then it will be loaded by JVM and since the interface file name is Main.class JVM will search for the static main method with String [] argument in Main.class and JVM will execute it.

Flow Diagram

classflowchart (Small).png

Answer: Yes we can run a static method in an Interface.

Did you find this article valuable?

Support Hritik manbattulwar by becoming a sponsor. Any amount is appreciated!