views:

134

answers:

3

Hi,

In Java, Is there a way to prevent extending an interface.

Since final cannot be added to an interface , i was curious to know whether there was a way if any, to prevent extending an Interface.

+2  A: 

There is no way to prevent extending an interface.

You could detect if someone has extended your interface at runtime using reflection.

Mark Byers
@Mark Can you elaborate on how can we find whether interface has been extended through reflection ?
JWhiz
@JWhiz: Your second question is very similar to this one: http://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface The only difference is that you are interested in interfaces, not classes, but the technique is the same.
Mark Byers
+2  A: 

The problem here is a conceptual one. Interfaces are meant to be extended because they can't be used as-is.

What you could do is put the interface inside a package and give it default visibility. With that only classes inside that package can implement that interface.

But with that solution you also lose the possibility to use the interface outside that package, so it is no real solution.

Johannes Wachter
I think he means that another interface is extended from the given interface.
lasseespeholt
Right, but the concept is still the key: an interface is just a way of saying that certain methods work in a certain way. Extending an interface is then just saying that there's some other interface in the system. It doesn't make sense to prohibit defining an interface in the same way that the "final" keyword works with classes, where actual code may end up being used in ways contrary to the original design if that class is extended.
Wez Furlong
A: 

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

I gave two answers.

  1. Yes, through byte code engineering. The resulting interface can not be extended but has no practical value
  2. Yes, annotations are interfaces that cannot be extended by other interfaces.

In addition, you can put the interface inside a class, give it the private access modifier, and make sure no interface in that class file extends it.

emory