Java 子类中的泛型和有界参数
Java Generics and Bounded parameters in subclasses
我正在尝试了解如何在接口中以有界类型参数的形式使用泛型。在这种情况下,为了避免在具体实现中使用有界参数时进行强制转换,但我遇到了一个问题。我将使用以下示例来说明我的问题:
有一个接口和两个具体实现
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 class 不能编译:我正在尝试使用比接口中发布方法的契约。那么我如何使用泛型来避免在 NewsPaperPublisher class 的 publish() 方法中强制转换?
您想使界面通用。
public interface Publisher <T extends Publication> {
void publish(T publication);
}
然后,您可以只写 Publisher<Newspaper>
和 Publisher<Magazine>
.
而不是 NewspaperPublisher
和 MagazinePublisher
或者如果你想根据类型提供不同的实现,你可以这样写
public class NewspaperPublisher implements Publisher<Newspaper> {
@Override
public void publish(Newspaper publication) {
// do some stuff
}
}
我正在尝试了解如何在接口中以有界类型参数的形式使用泛型。在这种情况下,为了避免在具体实现中使用有界参数时进行强制转换,但我遇到了一个问题。我将使用以下示例来说明我的问题:
有一个接口和两个具体实现
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 class 不能编译:我正在尝试使用比接口中发布方法的契约。那么我如何使用泛型来避免在 NewsPaperPublisher class 的 publish() 方法中强制转换?
您想使界面通用。
public interface Publisher <T extends Publication> {
void publish(T publication);
}
然后,您可以只写 Publisher<Newspaper>
和 Publisher<Magazine>
.
NewspaperPublisher
和 MagazinePublisher
或者如果你想根据类型提供不同的实现,你可以这样写
public class NewspaperPublisher implements Publisher<Newspaper> {
@Override
public void publish(Newspaper publication) {
// do some stuff
}
}