Can you write an interface that cannot be implemented?

This is due to the final interface in java . Among the discussions was that the concept of final with respect to interfaces is ambiguous. Will the end interface mean that it cannot have subinterfaces? Does this mean that it cannot have an implementation?

This question is first: can you write the final interface so that the compiler prevents you from implementing it?

+4
source share
3 answers

As I will show, you can implement the interface above using a proxy. A more meaningful question is why are you trying to make an unimplementable interface? Even as a philosophical moment, it seems rather petty.

import java.lang.reflect.Proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; class NoFinal { public static void main(String[] a) throws Throwable { FinalInterface o = (FinalInterface) Proxy.newProxyInstance(FinalInterface.class.getClassLoader(), new Class[]{FinalInterface.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { System.out.println(method); return null; } }); Method[] methods = FinalInterface.class.getDeclaredMethods(); methods[0].invoke(o, new Object[]{null}); methods[1].invoke(o, new Object[]{null}); } } 

This will not give a compilation error or runtime, and it shows that you can create a real instance of this interface using both methods called.

+4
source

I present the following as an interface, so that implementation will be prevented at compile time.

 interface FinalInterface { class Types { private class Alpha { } private class Beta { } } void method ( Types . Alpha param ) ; void method ( Types . Beta param ) ; } 
+2
source

Technically, you can by specifying options that are not available to developers, for example, in the same package as the interface, with visibility in the package.

But that makes no sense. In this case, this interface is completely useless.

Update: One application comes to my mind, but this should not be done. If you want to use interfaces for constant definitions, to free up a bunch of modifier that the interface assumes, but you do not want to use the anti-template to implement the interface for constants only.

+1
source

All Articles