Search code examples
javalanguage-featureslanguage-design

interface for only certain classes?


Can you create an interface which can only be applied to certain classes and subclasses?

If my interface is only added to different subclasses of JComponent, and I need to refer to both the methods of JComponent and my interface... how should I do this? Off the top of my head I can accomplish this by adding methods from JComponent to my interface.

This seems clumsy. What is a better way to do this?


Solution

  • The obvious solution is to add a method to your interface that returns the component (which may be this).

    JComponent getComponent();
    

    Or even genericise your interface:

     public interface MyInterface<C extends JComponent> {
         C getComponent();
         [...]
     }
    

    It's not great design, but it should work.