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?
-
2Which JDK you are using ?Suresh Atta– Suresh Atta2015年09月15日 08:56:03 +00:00Commented Sep 15, 2015 at 8:56
-
@sᴜʀᴇsʜᴀᴛᴛᴀ it is 1.8Danyal Sandeelo– Danyal Sandeelo2015年09月15日 09:02:35 +00:00Commented Sep 15, 2015 at 9:02
-
That's a new feature added in 1.8 :)Suresh Atta– Suresh Atta2015年09月15日 09:08:00 +00:00Commented Sep 15, 2015 at 9:08
-
my whole life is a lie ;-) implementation in interfaces, it brings a new paradigm in java interfaces..Danyal Sandeelo– Danyal Sandeelo2015年09月15日 09:11:12 +00:00Commented Sep 15, 2015 at 9:11
-
Welcome to Narnia ;)Suresh Atta– Suresh Atta2015年09月15日 09:13:28 +00:00Commented Sep 15, 2015 at 9:13
2 Answers 2
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
5 Comments
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.