How to prevent interface expansion

In Java, is there a way to prevent interface expansion.

Since final cannot be added to the interface , I was curious to know if there is a way, if any, to prevent the extension of the interface.

+6
java oop interface
source share
3 answers

Unable to prevent interface extension.

You may find that someone has expanded your interface at runtime using reflection.

+2
source share

The problem here is conceptual. Interfaces are intended to be expanded because they cannot be used as is.

What you can do is put the interface inside the package and give it the default visibility. However, only classes inside this package can implement this interface.

But with this solution, you also lose the ability to use the interface outside of this package, so it is not a real solution.

+3
source share

This is very similar to the previously asked question - the final interface in java .

I gave two answers.

  • Yes, by creating byte code . The resulting interface cannot be extended, but it has no practical value.
  • Yes, annotations are interfaces that cannot be extended by other interfaces.

In addition, you can put an interface inside a class, give it a private access modifier, and make sure that there is no interface in this class.

0
source share

All Articles