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 {@Overridepublic void sell() {System.out.println("sell books");}}
public class GoodsTest {public static void main(String[] args) {//定义book相关的ListList<Book> books=new ArrayList<Book>();books.add(new Book());books.add(new Book());//定义chothes相关的ListList<Clothes> clothes=new ArrayList<Clothes>();clothes.add(new Clothes());clothes.add(new Clothes());//定义shoes相关的ListList<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);}}