• java_泛型,设置类型通配符的上限


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

    
    
  • 相关阅读:
    git命令
    svg学习系列02-简单的svg图形和线条
    svg学习系列01-svg简介
    jQuery分页插件
    svg简介
    css3选择器
    sublime使用
    HTML5新特性
    html新的语义化标签和表单控件
    DOM详解
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720461.html
Copyright © 2020-2023  润新知