views:

112

answers:

3

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?

+6  A: 

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.

Tom Hawtin - tackline
+1  A: 

There might be scenarios where this won't work, but using generics lets you specify several types:

interface Foo { void frobulize(); }

class Bar {
    <T extends JComponent & Foo> String doFoo(T obj){
        obj.frobulize();
        return obj.getToolTipText();
    }
}

If you want the objects as fields on a non-parametrized type you can cheat with factory methods:

class Quux {
    private final Foo foo;
    private final JComponent component;
    private Quux(Foo f, JComponent c){
        foo = f;
        component = c;
        assert foo == component;
    }
    public static <T extends JComponent & Foo> Quux create(T fc){
        return new Quux(fc, fc);
    }
}
gustafc
A: 

Why would you do this?

Interfaces by their very nature shouldn't be restricted in this way and having to do so, is to me, indicative that your design is at the least you're over complicated or worse flawed in some way.

I think so long as the interface is clearly named and captures a single concept then it's served its purpose.

Nick Holt