无界通配符、有界通配符、extends可取、super可存

CEOjava

package com.example.genericdemo;

class CEO extends Manager {
}

class Manager extends Employee {
}

class Employee {
}

Point

package com.example.genericdemo;

/**
 * 一、泛型类 你传进去的是什么,T就表明什么类型
 */
class Point<T> {// 此处能够随便写标识符号
	private T x;
	private T y;

	public Point(T x, T y) {
		this.x = x;
		this.y = y;
	}

	public Point() {

	}

	public void setX(T x) {// 做为参数
		this.x = x;
	}

	public void setY(T y) {
		this.y = y;
	}

	public T getX() {// 做为返回值
		return this.x;
	}

	public T getY() {
		return this.y;
	}
}

MainActivity

package com.example.genericdemo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/**
		 * 一、通配符 泛型变量T不能在代码用于建立变量,只能在类,接口,函数中声明之后,才能使用。
		 * 而无边界通配符?则只能用于填充泛型变量T,表示通配任何类型
		 */
		@SuppressWarnings("unused")
		Point<?> point;

		point = new Point<Integer>(3, 3);
		point = new Point<Float>(4.3f, 4.3f);
		point = new Point<Double>(4.3d, 4.90d);
		point = new Point<Long>(12l, 23l);
		point = new Point<Object>();

		/**
		 * ? extends Number
		 * 一、只有数值类型才能赋值给point
		 * 二、利用<? extends,Number>定义的变量,只可取其中的值,不可修改
		 */
		@SuppressWarnings("unused")
		Point<? extends Number> point1;
		point1 = new Point<Integer>(3, 3);
		point1 = new Point<Float>(4.3f, 4.3f);
		point1 = new Point<Double>(4.3d, 4.90d);
		point1 = new Point<Long>(12l, 23l);
		//可取,不可存
		Number x = point1.getX();
		point1.setX(new Integer(222));// 报错
		//之接受数值类型
		point1 = new Point<Object>();// 报错

		/**
		 * 一、? super Manager,即Manager及其父类
		 */
		List<? super Manager> list;
		list = new ArrayList<Manager>();
		list = new ArrayList<Employee>();
		// 如下报错
		list = new ArrayList<CEO>();// 报错

		/**
		 * 一、正由于Manager和CEO都是Employee的子类,在传进去list.add()后,会被强制转换为Employee!
		 * 二、但Employee不必定是<? super Manager>的子类,因此不能肯定,不能肯定的,确定是不容许的,因此会报编译错误
		 */
		list.add(new Employee());// 报错
		list.add(new Manager());
		list.add(new CEO());


		/**
		 * ◆ 若是你想从一个数据类型里获取数据,使用 ? extends 通配符(能取不能存) 
		 * ◆ 若是你想把对象写入一个数据结构里,使用 ? super 通配符(能存不能取) 
		 * ◆ 若是你既想存,又想取,那就别用通配符。
		 */
	}

}