views:

108

answers:

3

I have two questions really:

1) When would you use a package-private interface?

2) Is there a way to have a public interface which is closed for implementation outside its package?

+4  A: 

1) when the interface is only needed in the scope of your package. For example an interface could make your code more readable, but the callers of the package have no need for it.

2) No, this isn't possible. See this link for more info. An interface defines no implementation. How could you close it for implementation then?

kgiannakakis
A: 

1) You may have utility methods used by multiple classes in your package which should never be called externally. Or they may be only needed by one class, but that class is so large you want to move some methods to another class for maintainability.

2) I would have to try it out (sorry, I'm rushing out the door now), but you might be able to effectively do that by declaring a protected default constructor in the interface.

dj_segfault
You can't declare constructors in an interface, note. Above note is right, if it's public, it can be implemented anywhere.
Sean Owen
+2  A: 

Package private interfaces are only useful in cases such implementations of the strategy pattern, where by there are several implementations that you may wish to use but dont want the world to be aware of the types.

mP