Can an interface be declared as final in Java?
Interfaces are 100% abstract and the only way to create an instance of an interface is to instantiate a class that implements it. Allowing interfaces to be final
is completely pointless.
EDIT The questions is not as outright outrageous as I first thought. A final interface is one that cannot be extended by other interfaces but can be implemented ostensibly makes sense.
I could think of one difference between a final class and a final interface. Extending a class can compromise its integrity because it contains some state. Extending an interface simply adds operations and cannot compromise the integrity of the implementation because the interface is stateless on its own.
No. Trying to declare an interface as final in Java results in a compilation error. This is a language design decision - Java interfaces are meant to be extendable.
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.
From the Java Language Specification (Third Edition):
9.1.1.1 abstract Interfaces
Every interface is implicitly
abstract
. This modifier is obsolete and should not be used in new programs.
So, abstract
+ final
is sort of an oxymoron.
class
? They are talking interface
. Even so, my compiler says MyClass can either be abstract
or final
, not both. –
Suburbanite I tried it and apparently you can create a final interface in java. I have no idea why you would do this, but you can. This is how I did it.
Compile a non final interface. I saved the below code in FinalInterface.java. Then I compiled it.
interface FinalInterface { }
Run BCELifier on it. This created a file called FinalInterfaceCreator.java
Edit it. Look for a line similar to below and add ACC_FINAL.
_cg = new ClassGen("FinalInterface", "java.lang.Object", "FinalInterface.java", ACC_INTERFACE | ACC_ABSTRACT | ACC_FINAL , new String[] { });
Compile and run the edited FinalInterfaceCreator.java. This should overwrite the original FinalInterface.class file with a new one that is similar but final.
To test it, I created two new java files TestInterface and TestClass. TestInterface is an interface that extends FinalInterface and TestClass is a class that implements FinalInterface. The compiler refused to compile either because FinalInterface is final.
TestClass.java:2: cannot inherit from final FinalInterface
class TestClass implements FinalInterface
TestInterface.java:2: cannot inherit from final FinalInterface
interface TestInterface extends FinalInterface
In addition, I tried creating an instance of FinalInterface using dynamic proxies
class Main
{
public static void main ( String [ ] args )
{
Class < ? > ntrfc = FinalInterface . class ;
ClassLoader classLoader = ntrfc . getClassLoader ( ) ;
Class < ? > [ ] interfaces = { ntrfc } ;
java . lang . reflect . InvocationHandler invocationHandler = new java . lang . reflect . InvocationHandler ( )
{
public Object invoke ( Object proxy , java . lang . reflect . Method method , Object [ ] args )
{
return ( null ) ;
}
} ;
FinalInterface fi = ( FinalInterface ) ( java . lang . reflect . Proxy . newProxyInstance ( classLoader , interfaces , invocationHandler ) ) ;
}
}
This one compiled but did not run
Exception in thread "main" java.lang.ClassFormatError: Illegal class modifiers in class FinalInterface: 0x610
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:632)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
at Main.main(Main.java:6)
So the evidence suggests that you can create a final interface in java, but why would you want to?
While a final interface would still have uses, none of them are widely considered good practice.
A final interface could be used for
- defining constants. Generally considered a bad idea.
- meta-information to be examined via reflection, e.g. a package descriptor
- grouping together many public inner classes into one file. (I only suggest this is used when cut-and-pasting some sample code which has many classes as it saves you the hassle of creating a file for each class, inner classes are implicitly static)
You can do all these things with a non-final interface and marking an interface as final would not be as useful as a comment saysing you are using an interface for an incedental purpose and why you are doing so
Sealed interface
If you want to limit who can extend and implement the interface, you can use sealed
in Java 17+. See JEP 409: Sealed Classes.
sealed interface A permits B, C {}
final class B implements A {}
non-sealed interface C extends A {}
You have to permit both B
and C
. The class (B
) has to be final
, sealed
, or non-sealed
.
The interface (C
) has to be sealed
, or non-sealed
.
When designing APIs in Java I sometimes find a situation where a type in the API has to be Java interface, but the number of its implementations should be limited - e.g. only the APIs internals can implement it, not anyone else.
I realized I can now (since Java 1.6) restrict who implements an interface with the help of annotation processors (article on apidesign.org). This is the code:
package org.apidesign.demo.finalinterface;
import java.util.Collection;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
import org.openide.util.lookup.ServiceProvider;
@ServiceProvider(service = Processor.class)
@SupportedAnnotationTypes("*")
public final class FinalEnforcingProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
checkForViolations(roundEnv.getRootElements());
return true;
}
private void checkForViolations(Collection<? extends Element> all) {
for (Element e : all) {
if (e instanceof TypeElement) {
TypeElement te = (TypeElement) e;
/* exception for the only known implementation:
if ("org.apidesign.demo.finalinterface.AllowedImplementationTest".equals(
te.getQualifiedName().toString())
) continue;
*/
for (TypeMirror m : te.getInterfaces()) {
if (FinalInterface.class.getName().equals(m.toString())) {
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR, "Cannot implement FinalInterface", e
);
}
}
}
checkForViolations(e.getEnclosedElements());
}
}
}
Everytime somebody includes your API JAR on classpath and tries to compile against it, the Javac compiler invokes your annotation processor and let's you fail the compilation if it detects somebody else is trying to implement your interface.
I still prefer usage of final class for Client API - e.g. an API that others are only allowed to call, but when it is not possible, the trick with annotation processor is acceptable alternative.
-proc:none
command line option, and you no longer enforce the limitation... I'd rather make the class package private and seal the package... –
Sackcloth final means it can't be modified. If it's a class, it can't be modified by extending (methods can be modified by overriding, attribute's can't be modified; added attributes/methods can only be accessed as members of the 'subclass type'); if its a variable (attribute/local) then the value can't be modified after first assignment; if its a method, the implementation can't be modified (a final method can be overloaded but can't be overridden). There no point in declaring an interface final since there's normally no implementation to modify (default and static interface methods are not allowed to be final).
Instead of Declaring Interface as a Final, We can avoid Creating an Interface object.
Point of Creating Interface to implements its methods by its subclass. If we are defeating this purpose then I feel its a baseless.
If any have any other suggestions, kindly let us know
Whenever you create an annotation you are creating an interface that is in some ways effectively final.
© 2022 - 2024 — McMap. All rights reserved.
public final interface MyInterface {}
and see if it compiles. – Dependencyimplements
interface) but not extensible (interfaceextends
interface). Only guessing. – Suburbanite