Jake
Jake

Reputation: 15217

Generics question

Suppose I have:

public interface Action<S extends Shape> {
  public void start( S shape );
}

Why do I get the following?

public <S extends Shape> void performAction( Action<S> action, Shape shape ) {
  action.start(shape);  // error: cannot supply Shape
}

In other words, in the future, I might have subclasses of Shape and Actions that operate on them like:

Action<Rectangle>
Action<Blob>

I'd like to have a uniform interface that can apply Actions to a bunch of different subclasses of Shape.

Upvotes: 1

Views: 169

Answers (5)

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26108

I think you need something like this:

public <S extends Shape> void performAction(Action<S> action, S shape) {
     action.start(shape);
}

However in this case it not clear what value there is in using generics if all you are interested in is Shape and its subclasses. The code below would accomplish the same thing.

public interface Action {
    public void start(Shape someShape);
}

public void performAction(Action action, Shape someShape) {
    action.start(someShape); 
}

If however the Action class is completely generic and can be used with objects other than Shape and its subclasses then you could do the following:

public interface Action<S> {
    public void start(S target);
}

public <S> void performAction(Action<S> action, S target) {
    action.start(target);
}

Upvotes: 5

KLE
KLE

Reputation: 24159

For a basic need, I suggest:

public interface Action {
  public void start(Shape shape );
}

Or if you need to type them stronger, you could change the other:

public <S extends Shape> void performAction( Action<S> action, S shape ) {
  action.start(shape); 
}

Upvotes: 1

jjnguy
jjnguy

Reputation: 138864

I don't think you necessarily need generics in this case. Here is what I would do:

public interface Action {
  public void start( Shape someShape );
}

public void performAction( Action action, Shape someShape ) {
  action.start(someShape); 
}

Then you can pass any type that extends Shape into the method start().

Upvotes: 3

Tom
Tom

Reputation: 44821

Because the action is for a specialization of shape, not any shape.

Upvotes: 1

danben
danben

Reputation: 83220

The signature of start requires an S, but you are passing it a Shape.

Upvotes: 1

Related Questions