Java 泛型作为方法参数
例程源码:
import java.util.List;
public class GoodsSeller {
public void sellGoods(List<? extends Goods> goods){
//调用集合中的sell方法
for(Goods g:goods){
g.sell();
}
}
}
public class Book extends Goods {
@Override
public void sell() {
System.out.println("sell books");
}
}
public class GoodsTest {
public static void main(String[] args) {
//定义book相关的List
List<Book> books=new ArrayList<Book>();
books.add(new Book());
books.add(new Book());
//定义chothes相关的List
List<Clothes> clothes=new ArrayList<Clothes>();
clothes.add(new Clothes());
clothes.add(new Clothes());
//定义shoes相关的List
List<Shoes> shoes=new ArrayList<>();
shoes.add(new Shoes());
shoes.add(new Shoes());
GoodsSeller goodsSeller=new GoodsSeller();
goodsSeller.sellGoods(books);
goodsSeller.sellGoods(clothes);
goodsSeller.sellGoods(shoes);
}
}