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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With