简体   繁体   中英

Using wildcard type in java generics

I want to pass object of GameObject class which would also implement Collidable interface. How should it look like?

private boolean isCollision(GameObject<? extends Collidable> collid) {
}

How should it look like? collid must be instance of both GameObject and Collidable .

如果你想确保collid是一个GameObject Collidable ,你可以使用这个语法:

private <T extends GameObject & Collidable> boolean isCollision(T collid)

It may be easier to define an interface that extends GameObject and Collidable . Then declare your parameter to be of that type.

public interface CollidableGameObject extends GameObject, Collidable {
}

Then your method might be:

private boolean isCollision(CollidableGameObject collid) {
}

Unless I'm missing something, generics don't appear to be needed. If GameObject is not already an interface, consider making it one?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM