user1768830
user1768830

Reputation:

Java type parameter is hiding a generic type?

I have a generic class:

public class Widget<COMMAND> {
    // ...
}

So I can create instances of it like:

Widget<Fizz> fizzWidget = new Widget<Fizz>();

Then I have an ABC BaseWidgetProcessor, that I want accepting Widgets of any type:

public abstract class BaseWidgetProcessor<Widget<COMMAND>> {
    public abstract COMMAND process();
}

With concrete impls:

public abstract class AstroWidgetProcessor<Widget<COMMAND>> {
    @Override
    public COMMAND process() {
        // ...
    }
}

etc.

The problem is, with BaseWidgetProcessor:

public abstract class BaseWidgetProcessor<Widget<COMMAND>> {
    public abstract COMMAND process();
}

I get a syntax error:

Syntax error on token(s), misplaced construct(s)

When I change it to:

public abstract class BaseWidgetProcessor<Widget> {
    public abstract COMMAND process();
}

The error goes away, but now I get a compiler warning:

The type parameter Widget is hiding the type Widget

What is going on here?!? Why the error and then respective warning? What's the correct (syntactically) way to set this up?

Upvotes: 1

Views: 839

Answers (2)

Rapha&#235;l
Rapha&#235;l

Reputation: 3751

I think what you are looking for is:

public abstract class BaseWidgetProcessor<W extends Widget<C>, C> {
    public abstract C process(W widget);
}

I added W widget as argument to show a bit better the usage.

Now let's say that you have a widget named CoolWidget:

public class CoolWidget extends Widget<Integer> {}

To declare a CoolWidgetProcessor you would have to do:

public class CoolWidgetProcessor extends BaseWidgetProcessor<CoolWidget, Integer> {
    @Override
    public Integer process(CoolWidget widget) {
        // ...
    }
}

Upvotes: 2

Bohemian
Bohemian

Reputation: 425198

Try this:

public abstract class BaseWidgetProcessor<COMMAND> {

    protected Widget<COMMAND> widget;

    public BaseWidgetProcessor(Widget<COMMAND> widget) {
        this.widget = widget;
    }

    // presumably uses widget
    public abstract COMMAND process();
}

Upvotes: 2

Related Questions