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