package ming; import java.util.ArrayList; import java.util.Collection; import java.util.List; class Canvas { // ? extends Shape,定义了子类,所以List<Circle>可以用 public void drawAll(List<? extends Shape> shapes) { for (Shape s : shapes) { s.draw(this); } } } abstract class Shape { public abstract void draw(Canvas c); } class Circle extends Shape { public void draw(Canvas c) { System.out.println("在画布上 " + c + "画一个圆"); } } class Rectangle extends Shape { @Override public void draw(Canvas c) { System.out.println("在画布上 " + c + "画一个正方形"); } } public class Apple3Test { public static void main(String[] args) { // TODO Auto-generated method stub Canvas ca = new Canvas(); //-------------------------------------------------- List<Circle> list = new ArrayList<Circle>(); list.add(new Circle()); list.add(new Circle()); list.add(new Circle()); ca.drawAll(list); //---------------不设置上面代码会报错------------------------ ArrayList<Shape> li2 = new ArrayList<Shape>(); li2.add(new Circle()); li2.add(new Rectangle()); li2.add(new Circle()); ca.drawAll(li2); } }