Java 5.0添加了对协变返回类型的支持,即子类覆盖(即重写)基类方法时,返回的类型可以是基类方法返回类型的子类。协变返回类型允许返回更为具体的类型。
下面通过一个简单的例子来演示一下:
package Animal;
public class CovariantDemo {
public static void main(String[] args) {
Animal animal=new Animal();
Food food=animal.behavior();
food.eat();
Dog dog=new Dog();
Bone bone=dog.behavior();
bone.eat();
}
}
//基类
class Animal{
public Food behavior(){
System.out.println("Animal:");
return new Food();
}
}
//子类
class Dog extends Animal{
@Override
public Bone behavior(){
System.out.println("Dog:");
return new Bone();
}
}
class Food{
public void eat(){
System.out.println("Animal like to eat food");
}
}
class Bone extends Food{
@Override
public void eat(){
System.out.println("Dogs like to eat bones");
}
}
解析:这里可以看到,子类Dog里面的behavior()方法返回的是父类中的返回类型的子类。
利用里氏替换方法:任何基类可以出现的地方,子类一定可以出现。
参考文章:
https://windcoder.com/javaxiebianfanhuileixingchutan
https://blog.csdn.net/huangwenyi1010/article/details/53454542