Java 泛型作为方法参数

蓝咒 提交于 2019-12-24 05:41:49

 

 

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

}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!