I was reading through the Map.Entry
interface, when I noticed it is a static
interface. I didn't quite understand what a static interface is, and how is it different from a regular interface?
public static interface Map.Entry<K,V>
This is the definition of the interface. Docs here: Map.Entry<K,V>.
Static methods in an interface since java8 Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
Java interface static method helps us in providing security by not allowing implementation classes to override them. We can't define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”.
Interface variables are static because java interfaces cannot be instantiated on their own. The value of the variable must be assigned in a static context in which no instance exists.
When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. For example, in the below java program, we are accessing static method m1() without creating any object of the Test class. Java.
I'm curious about the case when it's not an inner interface.
The static
modifier is only allowed on a nested classes or interfaces. In your example Entry
is nested inside the Map
interface.
For interfaces, the static
modifier is actually optional. The distinction makes no sense for interfaces since they contain no code that could access the outer this
anyway.
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