java - 在泛型中传递接口会做什么?
问题描述
public interface IComponent {
public void play();
public void setPlaybackSpeed();
public String getName();
}
public class Playlist implements IComponent {
public String playlistName;
public ArrayList<IComponent> playlist = new ArrayList();
public Playlist(String playlistName) {
this.playlistName = playlistName;
}
public void play(){
System.out.println("Playing the song");
}
public void setPlaybackSpeed(){
System.out.println("Setting the speed of playback to the specified value");
}
public String getName(){
return this.playlistName;
}
public void add(IComponent component){
}
public void remove(IComponent component){
}
}
我无法理解在线
public ArrayList<IComponent> playlist = new ArrayList();
当我们在泛型中传递任何类时,它只允许传递该类型数据的对象。当我们通过接口时会发生什么,会发生什么代码。
解决方案
您必须传递一个实现接口中调用的方法的实例。
这就是接口和泛型的美妙之处:您可以通过更改实现类以明确定义的方式更改行为。
我想说你的班级命名还有很多不足之处。我会选择Song
结束IComponent
。后者对我来说太笼统了。
您没有显示IComponent
界面,但如果它包含该play
方法对我来说很有意义。这种设计允许用户播放单个歌曲或整个播放列表。它被称为复合模式。
您在方法上还有更多工作要做。您应该能够轻松地实现play
、add
和remove
。
推荐阅读
- regex - 带有特殊字符的 MongoDB 查询
- ubuntu - 如何在 Ubuntu 上支持所有语言(字体)
- python - 如何在将“聚合”列分配给新列时对两列进行分组?
- vue.js - iframe 中的 Windows 事件
- r - 在数据框中每第四列插入 8 个空 (NA) 列
- java - 将相同的数据添加到多个折线图
- django - 无法删除对象 - ?csrfmiddlewaretoken= 出现在 urlbar (django) 中当前 URL 的末尾
- sql - 列“column1”的类型与 UNPIVOT 列表中指定的其他列的类型冲突
- pandas - 如果列值存在于另一个数据框中,则从数据框中提取数据
- swift - 在 Swift [UI] 中使用 UserDefaults 变得疯狂