我试图了解如何在界面中以有界类型参数的形式使用泛型。在这种情况下,为了避免在具体实现中使用有界参数时进行转换,但我遇到了问题。我将使用以下示例来说明我的问题:
有一个界面和两个具体的实现
public abstract class Publication {
}
public class Newspaper extends Publication {
}
public class Newspaper extends Publication {
}
然后我们有一个界面代表一个出版社,有两个具体实现,一个发布杂志和其他报纸
public interface Publisher {
public <T extends Publication >void publish(T publication);
}
以下是两个实现
//DOES NOT COMPILE
public class MagazinePublisher implements Publisher{
@Override
public void publish(Magazine publication) {
//do something with the magazine, its already the type we need without casting
}
}
//COMPILES but a cast is required to get the type I want
public class NewsPaperPublisher implements Publisher{
@Override
public void publish(Publication publication) {
// Now I need to cast
Newspaper newspaper = (Newspaper)publication;
//Do some stuff here
}
}
这个例子可能有点人为......我理解为什么MagazinePublisher类没有编译:我试图使用比发布方法的合同定义的更具体的类来实现该方法。界面。那么我如何使用泛型来避免在NewsPaperPublisher类的publish()方法中进行强制转换呢?
答案 0 :(得分:6)
您希望使界面通用。
public interface Publisher <T extends Publication> {
void publish(T publication);
}
然后,您只需撰写NewspaperPublisher
和MagazinePublisher
,而不是Publisher<Newspaper>
和Publisher<Magazine>
。
或者,如果您想根据类型提供不同的实现,您可以编写类似
的内容public class NewspaperPublisher implements Publisher<Newspaper> {
@Override
public void publish(Newspaper publication) {
// do some stuff
}
}