Why can't the interface be final?

JLS 2.13.1 Interface Modifiers

An interface cannot be final, since the implementation of such a class can never be completed.

If I can write the creation of static inner classes in an interface, I can provide an implementation in it, so why is this a limitation

interface Type { // Normal class Value { private Value() { } public void print() { System.out.println("Test"); } } public final Value value = new Value(); } 
+6
source share
4 answers

BTW: nested classes are not available when this restriction was first defined, so the real question may be why this restriction was not removed.


A final class cannot have any subclasses. It is recommended to use only interfaces for defining methods (approaches) of subclasses, therefore they are contradictory.

You can use interfaces for other things.

  • annotations
  • Javadocs
  • constants
  • defining only nested classes.

but this is due to the purpose of the interface.

+4
source

Well in interfaces, you cannot provide any form of implementation at all: even static methods. It makes no sense to make any method final, because they have not yet been implemented.

Code Examples:

If I say that I have an interface named IExample and its concrete implementation Example :

 interface IExample{ public final void run(); } class Example implements IExample{ // wait! I can't override because it final! but it yet to be implemented?! public void run(){ } } 
+9
source

β€œWhen the final keyword appears in a class declaration, it means that a class can never be subclassed or overridden. This prevents over-specialization of a particular class. In a way, the person who created the class considered any further changes to be tangential in their main purpose.”

Link: Final

An interface is a behavior, not an implementation, so it makes no sense to be final.

+1
source

If I can write the creation of static inner classes in an interface, I can provide an implementation in it, so why is this a limitation

Yes, you can declare an inner class there, but the point is that the final interface will be an interface that cannot be implemented. Any class that implements it will violate the final constraint. Java developers have come to the conclusion that this does not make much sense, and since there are no convincing examples of using final interfaces with nested classes * there is no excuse to ease this restriction.

* - I will not argue that it was impossible to come up with a precedent. However, I have never heard that people write interfaces with inner classes, but the intention was that the interface should not be implemented.

0
source

Source: https://habr.com/ru/post/925016/


All Articles