Java泛型和子类中的有界参数

xtr*_*dit 0 java generics

我试图了解如何在接口中以有界类型参数的形式使用泛型.在这种情况下,为了避免在具体实现中使用有界参数时进行转换,但我遇到了问题.我将使用以下示例来说明我的问题:

有一个接口和两个具体的实现

public abstract class Publication {
}


public class Newspaper extends Publication {
}


public class Newspaper extends Publication {
}
Run Code Online (Sandbox Code Playgroud)

然后我们有一个界面代表一个出版社,有两个具体实现,一个发布杂志和其他报纸

public interface Publisher {
    public <T extends Publication >void publish(T publication);
}
Run Code Online (Sandbox Code Playgroud)

这是两个实现

//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 
   }
}
Run Code Online (Sandbox Code Playgroud)

这个例子可能有点人为......我理解为什么MagazinePublisher类没有编译:我试图用一个比接口中的publish方法的契约定义的更具体的类来实现该方法.那么我如何使用泛型来避免NewsPaperPublisher类的publish()方法中的强制转换呢?

Daw*_*ica 6

您想使接口通用.

public interface Publisher <T extends Publication> {
    void publish(T publication);
}
Run Code Online (Sandbox Code Playgroud)

然后,而不是NewspaperPublisherMagazinePublisher,你可以写Publisher<Newspaper>Publisher<Magazine>.

或者,如果您想根据类型提供不同的实现,您可以编写类似的内容

public class NewspaperPublisher implements Publisher<Newspaper> {
    @Override
    public void publish(Newspaper publication) {
        // do some stuff
    }
}
Run Code Online (Sandbox Code Playgroud)