Java 5.0添加了对协变返回类型的支持,即子类覆盖(即重写)基类方法时,返回的类型可以是基类方法返回类型的子类。协变返回类型允许返回更为具体的类型。
public class CCCC {
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");
}
}