Java中协变返回类型的简单理解

在Java SE5中添加了协变返回类型,定义为子类重写父类方法时,返回类型可以是父类返回类型的子类。

实例:

public class test {
	public static void main(String[] args) {
		Plant plant = new Plant();
		Flower flower = new Flower();
		plant = flower.kind();
		System.out.println("未使用协变返回类型:"+plant);//未使用协变返回类型
		flower = new WhiteRose();
		plant = flower.kind();
		System.out.println("使用协变返回类型:"+plant);//使用协变返回类型
	}
}
class Flower{//花类
	Plant kind(){
		return new Plant();
	}
}
class Plant{//植物类
	public String toString() {
		return "Plant";
	}
}
class Rose extends Plant{//玫瑰类
	public String toString() {
		return "Rose";
	}
}
class WhiteRose extends Flower{//白玫瑰类
	Rose kind(){
		return new Rose();
	}
}

输出结果:

未使用协变返回类型:Plant
使用协变返回类型:Rose


猜你喜欢

转载自blog.csdn.net/edison_style/article/details/80418711