开发者

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.


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);
}


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().


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


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


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); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜