Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why interface cannot be final?

Tags:

java

interface

JLS 2.13.1 Interface Modifiers

An interface cannot be final, because the implementation of such a class could never be completed.

If I can write create static inner classes in interface I can provide implementation in it so why is such restriction

interface Type {

    // Normal
    class Value {
        private Value() {
        }

        public void print() {
            System.out.println("Test");
        }
    }

    public final Value value = new Value();
}
like image 889
Amit Deshpande Avatar asked Sep 10 '12 12:09

Amit Deshpande


2 Answers

Well in Interfaces you cannot provide any form of implementation at all: Not even static methods. It doesn't make sense to make any method final because they're yet to be implemented.

Code Examples:

If let say 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's final! but it's yet to be implemented?!
    public void run(){ 
        
    }

}
like image 98
mauris Avatar answered Sep 23 '22 17:09

mauris


BTW: nested classes were not available when this restriction was first defined, so really the question might be why this restriction was not lifted.


A final class cannot have any sub-classes. It is considered best practice to only use interfaces for defining method(s) of sub-classes, so the two are contradictory.

You can use interfaces for other things

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

but these are incidental to the purpose of an interface.

like image 36
Peter Lawrey Avatar answered Sep 20 '22 17:09

Peter Lawrey