Java 5.0添加了对协变返回类型的支持,即子类覆盖(即重写)基类方法时,返回的类型可以是基类方法返回类型的子类。协变返回类型允许返回更为具体的类型。

    1. public class CCCC {
    2. public static void main(String[] args) {
    3. Animal animal=new Animal();
    4. Food food=animal.behavior();
    5. food.eat();
    6. Dog dog=new Dog();
    7. Bone bone=dog.behavior();
    8. bone.eat();
    9. }
    10. }
    11. //基类
    12. class Animal{
    13. public Food behavior(){
    14. System.out.println("Animal:");
    15. return new Food();
    16. }
    17. }
    18. //子类
    19. class Dog extends Animal{
    20. @Override
    21. public Bone behavior(){
    22. System.out.println("Dog:");
    23. return new Bone();
    24. }
    25. }
    26. class Food{
    27. public void eat(){
    28. System.out.println("Animal like to eat food");
    29. }
    30. }
    31. class Bone extends Food {
    32. @Override
    33. public void eat() {
    34. System.out.println("Dogs like to eat bones");
    35. }
    36. }