【问题标题】:What is the benefit of base class variable holding derived class object?基类变量持有派生类对象有什么好处?
【发布时间】:2015-10-01 21:05:55
【问题描述】:

我知道可以将基类变量保存为派生类对象。如下图......

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
    }
}

那么这个有什么用呢?我仍然没有看到任何好处。有人可以解释一下,可能是我错过了什么。谢谢。

【问题讨论】:

    标签: oop inheritance


    【解决方案1】:

    在这种情况下,变量是从子类变量初始化的,它并不是非常有用。有用性有两种情况:

    • 当你有一个带有基类类型的函数参数,并且你传入一个子类对象作为实际参数。

      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 正在初始化哪个子类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-11
      • 2018-04-29
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2011-07-20
      相关资源
      最近更新 更多