Java wildcard set type and the set upper limit type parameters

One o'clock eye

Use List <?> This form that indicates that this could be any generic collection List List of the parent class.

But there is a special situation, we do not want this List <?> Is any generic List parent, just want to show that it is some sort of generic List parent. 

For example: We need a generic representation, it can represent all Shape generic List parent, in order to meet this demand, Java Generics provide generic wildcard is limited.

Generic wildcard is restricted represented as follows:

List<? extends Shape>

Two real - drawing program implemented

1 Shape.java

// 定义一个抽象类Shape
public abstract class Shape
{
   public abstract void draw(Canvas c);

}

2 Circle.java

// 定义Shape的子类Circle
public class Circle extends Shape {
    // 实现画图方法,以打印字符串来模拟画图方法实现
    public void draw( Canvas c ) {
        System.out.println("在" + c + "画布" + "上画一个圆");
    }

}

3 Rectangle.java

// 定义Shape的子类Rectangle
public class Rectangle extends Shape
{
   // 实现画图方法,以打印字符串来模拟画图方法实现
   public void draw(Canvas c)
   {
      System.out.println("把一个矩形画在画布" + c + "上");
   }
}

4 Canvas.java

import java.util.*;
public class Canvas
{
   // // 同时在画布上绘制多个形状
// public void drawAll(List<Shape> shapes)
// {
//    for (Shape s : shapes)
//    {
//       s.draw(this);
//    }
// }
// public void drawAll(List<?> shapes)
// {
//    for (Object obj : shapes)
//    {
//       Shape s = (Shape)obj;
//       s.draw(this);
//    }
// }
   // 同时在画布上绘制多个形状,使用被限制的泛型通配符
   public void drawAll(List<? extends Shape> shapes)
   {
      for (Shape s : shapes)
      {
         s.draw(this);
      }
   }

   @Override
   public String toString() {
      return "彩色";
   }

   public static void main( String[] args)
   {
      List<Circle> circleList = new ArrayList<Circle>();
      circleList.add(new Circle());
      Canvas c = new Canvas();
      c.drawAll(circleList);
   }
}

Run 5

In a circle on a color canvas painting

Three limit parameter set type

1:00 eye

Java generic type not only allows setting an upper limit in the use of wildcard parameter, the upper limit may be set when defining the type parameter is used to record the actual type indicates the type parameter must be an upper limit type, or the upper limit type subclass. 

The syntax format:

Apple<T extends Number>

2 combat

public class Apple<T extends Number>
{
   T col;
   public static void main(String[] args)
   {
      Apple<Integer> ai = new Apple<>();
      Apple<Double> ad = new Apple<>();
      // 下面代码将引起编译异常,下面代码试图把String类型传给T形参
      // 但String不是Number的子类型,所以引发编译错误
      //Apple<String> as = new Apple<>();       // ①
   }
}

3 Description

Apple defines a generic class type parameter class is the upper limit of the Apple Number class, which indicates that the use of a T-type Apple parameter passed only the actual type arguments or subclass Number Number class.

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/94327675