协变和抗变

在OO中,协变是指按照继承链正向改变,抗变是指逆向改变.

class Grain
{
	public String toString()
	{
		return "Grain";
	}
}

class Wheat extends Grain
{
	public String toString()
	{
		return "Wheat";
	}
}

class Mill
{
	Grain process(){
		return new Grain();
	}
}

//协变
class WheatMill extends Mill{
	Wheat process(){
	return new Wheat();
	}
}

//抗变
class KangBian extends Wheat
{
	Grain process()
	{
		return new Grain();
	}
}

public class NewTest{
	public static void main(String[] args)
	{
		Mill m = new Mill();
		Grain g = m.process();
		System.out.println(g);
		
		m = new WheatMill();
		g = m.process();
		System.out.println(g);
		
		KangBian k = new KangBian();
		g = k.process();
		System.out.println(g);
	}
}

<完>

你可能感兴趣的:(协变和抗变)