首页 > 解决方案 > 在泛型中传递接口会做什么?

问题描述

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();

当我们在泛型中传递任何类时,它只允许传递该类型数据的对象。当我们通过接口时会发生什么,会发生什么代码。

标签: javagenerics

解决方案


您必须传递一个实现接口中调用的方法的实例。

这就是接口和泛型的美妙之处:您可以通过更改实现类以明确定义的方式更改行为。

我想说你的班级命名还有很多不足之处。我会选择Song结束IComponent。后者对我来说太笼统了。

您没有显示IComponent界面,但如果它包含该play方法对我来说很有意义。这种设计允许用户播放单个歌曲或整个播放列表。它被称为复合模式。

您在方法上还有更多工作要做。您应该能够轻松地实现playaddremove


推荐阅读