Oop 基类变量持有派生类对象有什么好处?

Oop 基类变量持有派生类对象有什么好处?,oop,inheritance,Oop,Inheritance,我知道基类变量保存派生类对象是可能的。就像下面 class Animal { public void printName() { System.out.println("Print your name"); } } public class Tiger extend Animal { public void Print() { System.out.println("My Name"); } public

我知道基类变量保存派生类对象是可能的。就像下面

class Animal
{
    public void printName()
    {
        System.out.println("Print your name");
    }
} 

public class Tiger extend Animal
{
    public void Print()
    {
        System.out.println("My Name");
    }
    public void static main(String args[])
    {
        Animal type1 = new Tiger();
        //with this new created type1 varibale. I can only access members of Animal class.
        type1.PrintName() // valid
        type1.Print() //In-valid
    }
}

那么这有什么用呢?我仍然看不到任何好处。有人能给我解释一下吗,也许我遗漏了什么。谢谢。

在这种情况下,如果变量是从子类变量初始化的,那么它就没有多大用处了。在两种情况下有用:

  • 当您有一个基类类型的函数参数,并将一个子类对象作为实际参数传入时

    void CareForAnimal(Animal anm) {
        anm.Feed();
        anm.Sleep();
    }
    
    虽然从技术上讲,允许您使用常规变量无法使用的形式参数进行操作是可能的,但作为语言设计师,要使这些参数有所不同并没有多大好处,这是非常复杂的

  • 如果有一个基类变量是从一个本身为虚拟的方法的结果初始化的:

    Animal Breed(Animal father, Animal mother) {
        Animal child = mother.mater(father);
    
        child.Bathe();
        child.Nurse(mother);
    
        return child;
    }
    
现在,您不知道正在初始化哪个子类
child