I have the following abstract class:
public abstract class MyObject<T extends DescriptionItem> {
protected abstract MyObject generate(T item);
}
which has the following subclass:
public class AudioObject extends MyObject<PlayNowDescriptionItem> {
@Override
protected MyObject generate(PlayNowDescriptionItem item) {
//do something
}
}
PlayNowDescriptionItem extends DescriptionItem. I also have a factory class for generating objects.
public class ObjectFactory {
public MyObject generateCastObject(DescriptionItem item) {
if (item instanceof PlayNowDescriptionItem) {
return new AudioObject(context).generate(item);
}
I thought that this would work fine because PlayNowDescriptionItem is a child of DescriptionItem, but i get an error on the following line.
return new AudioObject(context).generate(item);
PlayNowDecriptionItem in AudioObject cannot be applied to DescriptionItem.
Can anyone see what i'm doing wrong here?
You need to cast your DescriptionItem
to PlayNowDescriptionItem
like this:
return new AudioObject(context).generate((PlayNowDescriptionItem)item);
as you defined the generate method to accept a subclass of DescriptionItem (please note that an object of class PlayNowDescriptionItem
is also an object of class DescriptionItem
but the contrary is not always valid, eg. could be a subclass PlayAfterDescriptionItem
that's is not a PlayNowDescriptionItem
)
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.