Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation within the Interface - Java

Tags:

java

We know that we can't implement functions in interfaces in java.

I just tried

public interface InvoiceService {

public static void getData(){
    System.out.print("this is my data");
 }
}

I am able to execute this function, why is it like that? is it because the function is defined as static and static variables can be accessed using class name directly without creating an object?

like image 526
Danyal Sandeelo Avatar asked Jan 31 '26 01:01

Danyal Sandeelo


2 Answers

Because you might be using Java 8. In Java 8 you can add static methods in interfaces as well as default methods. Please read more about static and default methods in Java 8 documentation

like image 139
Jawad Avatar answered Feb 02 '26 17:02

Jawad


is it because the function is defined as static and static variables can be accessed using class name directly without creating an object?

You are using Java8 it seems and you just implemented a default method

Yes, that method need not to ovveride by any of the implemented classes and belongs to interface.

And yes you need not to create an instance to access it. You can access it by interface name itself.

And since that is a static method you can use that as any normal utility method

From doc again,

If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

like image 45
Suresh Atta Avatar answered Feb 02 '26 16:02

Suresh Atta