Final interface in Java?

前端 未结 10 2122
情话喂你
情话喂你 2020-12-03 09:37

Can an interface be declared as final in Java?

10条回答
  •  一个人的身影
    2020-12-03 10:15

    No. The Java Language Specification section 9.1.1. Interface Modifiers states the following:

    An interface declaration may include interface modifiers.

    InterfaceModifier:
      (one of)
      Annotation public protected private
      abstract static strictfp
    

    As can be seen, the list does not include final.

    Why was the language designed this way?

    If an interface was declared final I suppose it could have meant that

    • No other interface could extend it

      This would be a non-sensical restriction. The reasons for why it can be useful to declare a class final, is to protect state invariants, prohibit overriding of all methods at once, etc. None of these restrictions makes sense for interfaces. (There is no state, and all methods must be overridden.)

    • No class could implement the interface

      This obviously defeats the purpose of an interface altogether.

提交回复
热议问题