0

I am curious to know if we can make an interface static in java. I tried but getting the below error. I also want to know why it is happening.

error: modifier static not allowed here
static interface Interf{
       ^
1 error

Thanks in advance.

prateek
  • 11
  • 1
  • 3
    What do you want to achieve by doing that ? – Florent Bayle May 27 '21 at 11:09
  • and `interface` is `static` – Lino May 27 '21 at 11:10
  • 2
    *modifier `static` not allowed here* does not leave much space for interpretation, does it? – deHaar May 27 '21 at 11:11
  • 3
    Interfaces are static by default so the keyword is superfluous here. Note that you also can't declare top-level classes static. The `static` keyword on a class is only allowed for inner classes and interface to declare there's no special relation to the outer class other than that acting as a namespace. – Thomas May 27 '21 at 11:11
  • 2
    Static for an inner class means "Don't keep a reference to my parent class as part of my state". Interfaces have no state, so the static keyword is meaningless for them. If you are trying to use the static keyword on a top-level type (whether it be class, interface, abstract class, record etc.), you can never use the static keyword in that context. If there is no parent, it doesn't make sense. – Michael May 27 '21 at 11:15
  • By the way, an interface can now be defined locally in Java 16+, as can an enum, per Java JEP 395 *Records*. – Basil Bourque May 27 '21 at 11:16
  • @Michael 'Static for an inner class' is a contradiction in terms. An inner class in Java is a nested class that isn't static. What you mean is 'static for a *nested* class'. – user207421 May 27 '21 at 11:50
  • @user207421 I meant "take an inner class, then add static to it". You're right that it could have been clearer but I can't edit it now. – Michael May 27 '21 at 11:54

0 Answers0