java – 如果是父实例,instanceof会返回true吗?

我有一个扩展Parent的Child类.

Parent child = new Child();

if (child instanceof Parent){
    // Do something
}

这会返回true还是false,为什么?

解决方法:

Yes,它会.为什么不呢?

因为孩子实际上是父母的一个实例.如果,您只想为孩子执行操作,则应检查

if (child instanceof Child){
}

但是你应该记住Scott Meyers的Effective C的以下声明:

“Anytime you find yourself writing
code of the form “if the object is of
type T1, then do something, but if
it’s of type T2, then do something
else,” slap yourself.

我认为也适用于这种情况.如果您想根据引用对象所属的类类型来执行某些操作,则以下代码结构应该可以帮助您.

注意:我没有编译它.

class Parent {
    public void doSomething() {
        System.out.println("I am the Parent, and I do as I like");
    }
}

class ChildA extends Parent {
    public void doSomething() {
        System.out.println("I am a child named A, but I have my own ways, different from Parent");
    }
}

class ChildB extends Parent {
    public void doSomething() {
        System.out.println("I am a child named B, but I have my own ways, different from my Parent and my siblings");
    }
}

public class Polymorphism101 {

    public static void main(String[] args) {

        Parent p = new Parent();
        p.doSomething();

        p = new ChildA();
        p.doSomething();

        p = new ChildB();
        p.doSomething();

    }

}

编辑:一个更好的例子

您可以开发绘图应用程序.绘制任何形状的应用程序.在这种情况下,您应该有一个抽象类型Shape.

出于某些目的;绘制所有形状;列出所有形状;找到一个形状或删除一个形状,你需要有一个形状列表.由于列表是父类型,因此它可以存储任何形状.

Shape接口/抽象类/虚拟类应该有一个抽象/纯虚函数Draw().因此,在您的DrawToDeviceLoop中,您只需为每个形状调用Draw(),您永远不需要检查它是什么形状.

Shape接口可以有一个抽象实现AbstractShape,它可以具有形状名称或id作为数据成员,以及GetName,Cleanup和其他具有所有形状共有功能的函数.

请记住,抽象类型无法实例化,因此无法实例化Shape本身,因为它也无法绘制.

上一篇:多态或更改变量Java的名称


下一篇:java – 如何使用多态而不是instanceof? (为什么?)