Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a static interface in java?

Tags:

java

interface

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>.

like image 497
brainydexter Avatar asked Dec 04 '11 10:12

brainydexter


People also ask

Can you have a static interface in Java?

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.

Why do we use static interface?

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”.

Are interfaces static?

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.

What is static in Java with example?

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.


1 Answers

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.

like image 97
Jörn Horstmann Avatar answered Sep 17 '22 22:09

Jörn Horstmann