Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are interfaces in Java 8 allowed to have the main method?

Tags:

java

java-8

Why are interfaces allowed to have a main method in Java 8?

As stated in below code it works fine and produces output properly.

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

Currently it is behaving like a class and I have executed interface with main method.

Why do we need this?

like image 428
akash Avatar asked Oct 23 '14 06:10

akash


People also ask

CAN interface have main method Java 8?

Yes, from Java8, interface allows static method. So we can write main method and execute it.

Why do we need default method in Java 8 interfaces?

Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.

CAN interfaces have main method?

It cannot have a method body. Java Interface also represents the IS-A relationship. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.

What benefit do we get by allowing a default method in interface?

Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces. In particular, default methods enable you to add methods that accept lambda expressions as parameters to existing interfaces.


2 Answers

Since Java 8, static methods are allowed in interfaces.

main() is a static method.

Hence, main() is allowed in interfaces.

We don't need this, since it wasn't allowed before, and yet we survived. But since static methods, by definition, are not bound to an instance of a class, but to the class itself, it makes sense to allow them in interfaces. It allows defining utility methods related to an interface (like the ones found in Collections, for example), in the interface itself, rather than a separate class).

There is no difference between class static methods and interface static methods.

like image 128
JB Nizet Avatar answered Sep 22 '22 11:09

JB Nizet


I second the answer of @jb-nizet. There is no "desparate need" for this, but it removes an unnecessary restriction. E.g. one example is, that you can now declare a factory method within the interface:

 public interface SomeService {     public static SomeService getInstance() {      // e.g. resolve via service provider interface    }     ...   } 

Before Java 8 we needed always a separate factory class. One favorite example is the google app engine API.

like image 39
cruftex Avatar answered Sep 26 '22 11:09

cruftex