如何将基类对象分配给父类引用?

时间:2014-06-14 16:25:30

标签: java inheritance parent-child

假设我们分别有一个名为ChildParent的基类和父类。

Parent b = new Child();
System.out.println(b instanceof Child);// prints true.
System.out.println(b instanceof Parent);//prints true.

那么为什么两个陈述都是真的呢?

3 个答案:

答案 0 :(得分:2)

如果B类扩展A类,那么B是A.例如,Circle是一个Shape。

能够将实例称为父类是一种面向对象语言的要求

请参阅Liskov substitution principle

答案 1 :(得分:1)

instanceof检查对象动态 类型的关系“IS”

Animal a = new Dog() //Dynamic type of a is Dog
d instanceof Animal // TRUE

因为狗是动物。

所以instanceof查看Animal的分支并发现Dog是Animal的孩子,因此返回true。

然而:

a instance of Dog // FALSE

因为动物不一定是狗

结论:X instanceof Y,为此,Y必须是X的父级或同一分支中相同类型的X

答案 2 :(得分:1)

instanceof运算符将对象与指定类型进行比较。您可以使用它来测试对象是否是类的实例,子类的实例或实现特定接口的类的实例。

了解更多Oracle Java Tutorial - The Type Comparison Operator instanceof

注意:使用instanceof运算符时,请注意null不是任何实例。

例如:

String name = null;
System.out.println((name instanceof String));  // prints false

您可能对Class#isAssignableFrom()

感兴趣
Parent p = new Child();
System.out.println(p.getClass().isAssignableFrom(Parent.class)); // return false
System.out.println(p.getClass().isAssignableFrom(Child.class));  // return true