如果是父实例,instanceof 是否返回 true?

发布于 2024-11-14 23:20:41 字数 191 浏览 5 评论 0原文

我有一个扩展ParentChild 类。

Parent child = new Child();

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

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

I have a class Child that extends Parent.

Parent child = new Child();

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

Does this return true or false, and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

楠木可依 2024-11-21 23:20:41

是的,会的。为什么不应该呢?

因为child实际上是Parent的一个实例。如果您只想对子项执行操作,您应该检查

if (child instanceof Child){
}

但是您应该记住 Scott Meyers 的《Effective C++》中的以下语句:

“任何时候你发现自己在写作
代码形式为“如果对象是
输入 T1,然后执行某些操作,但如果
它是 T2 类型,然后做一些事情
否则,”打自己一巴掌。

我认为这也适用于这种情况。如果您想根据引用对象所属的类类型做一些事情,以下代码结构应该可以帮助您。

<强>注意:我还没有编译它

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();
 
    }
 
}

编辑:一个更好的例子

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

出于以下目的:绘制所有形状;查找形状或删除形状,您需要有一个列表。 的 Shapes。由于该列表是父类型,因此它可以存储任何形状。

Shape 接口/抽象类/虚拟类 应该有一个。 >抽象/纯虚函数 Draw()。因此,在 DrawToDeviceLoop 中,您只需为每个形状调用 Draw(),而无需检查它的

Shape< 。 /code> 接口可以有一个抽象实现AbstractShape,它可以将形状名称或id作为数据成员以及GetName、Cleanup和其他具有所有形状通用功能的函数。

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

编辑2:多态性和异常处理 - user1955934询问“关于检查异常类怎么样”对于异常处理关于多态性的最佳实践是:

  1. 更喜欢(抛出)特定的异常 - 例如抛出 NumberFormatException 而不是 IllegalArgumentException
  2. 首先捕获最具体的异常 - 例如,如果您捕获首先,您永远不会到达应该处理更具体的 NumberFormatException 的 catch 块,因为它是 IllegalArgumentException 的子类。

因此,其原则上是相同的,如果需要以不同方式处理异常,则应定义子/特定类,并且应捕获特定异常(不检查instanceof)

以了解更多最佳实践异常处理。请参阅 9 个 Java 中处理异常的最佳实践异常的最佳实践 (C#)

编辑3:我承认这条规则有一个例外

因此,我正在使用遗留代码(用 C++ 编写),该代码大部分是在大约 15 年前编写的,它们总是检查子类是否执行某些操作行动。我被要求添加一些具有相同逻辑的代码,我告诉我的经理(他也是开发人员)我不能这样做,指向这个答案,然后我们讨论并接受了这个规则的例外。在我们的例子中,这个父类自 2000 年以来只有 2 个子类,并且我们看不到在不久的将来添加任何子类,由于核心代码的增长受到限制,我们决定不添加子类和当前的子类。 number 只是 2,检查类型会更有效,尤其是当代码一直这样编写时。

不过,这种检查的实例并不多,父级主要实现复杂的功能,并且它更多地用于共享代码,然后专门/区分它们。

Yes, it would. And why should it not?

Because child is in fact an instance of Parent. If, you want to perform an operation only for a child you should check

if (child instanceof Child){
}

However you should remember the following statement from Effective C++, by Scott Meyers :

"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.

which I think applies in this case too. If you want to doSomething based on what type of class the referenced object belongs to, the following code structure should help you with it.

NOTE: I have not compiled it.

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();
 
    }
 
}

EDIT: A better example

You could be developing a drawing application. An application that draws shapes of any kind. In that case, you should have an abstract type Shape.

For purpose(s) like; drawing all shapes; list all shapes; find a shape or delete a shape, you need to have a list of Shapes. Since the list is of a parent type, it can store any shapes.

The Shape interface/abstract class/virtual class should have an abstract/pure virtual function Draw(). So, in your DrawToDeviceLoop, you just call Draw() for each shape, you never need to check what shape it is.

The Shape interface can have an abstract implementation AbstractShape, which can have shape name or id as data members and GetName, Cleanup and other functions with functionality common to all shapes.

Remember an abstract type cannot be instantiated, so Shape itself cannot be instantiated, as it cannot be drawn either.

EDIT 2: Polymorphism and Exception Handling - user1955934 asked "What about checking for exception class" For exception handling the best practices with respect to polymorphism are:

  1. Prefer (to throw) specific exception - For example throw a NumberFormatException instead of IllegalArgumentException
  2. Catch the most specific exception first - For example, if you catch an IllegalArgumentException first, you will never reach the catch block that should handle the more specific NumberFormatException because it’s a subclass of the IllegalArgumentException.

So, its principally the same, if an exception needs to be handled differently, a child/specific class should be defined, and the specific exception should be caught (not checked instanceof)

To know more best practices on exception handling. See 9 Best practices to handle exception in Java and Best practices for exceptions (C#)

EDIT 3: I admit to an exception in this rule

So, I am working with a legacy code (written in C++), which has mostly been written about 15 years ago, where they always check for the child class to perform certain actions. I was asked to add some code with the same logic, and I told my manager (he is a Dev too) I cannot do this, pointing to this answer, and then we discussed and accepted to this exception to the rule. In our case, this parent class has had just 2 children since the year 2000, and we do not see any child being added in the near future, with the core code limited for growth, we decided that with no addition to child classes and current number being just 2, it is more efficient to check for type, especially when that is how the code has been written, since ever.

There aren't many instances of this check too though, the parent implements the complicated functionalities mostly and it exists more for sharing code then specializing/differentiating them.

梦亿 2024-11-21 23:20:41

instanceof 如果它是子类,将返回 true...

文档实例

instanceof will return true if it's a subclass...

instanceof Documentation

梦里寻她 2024-11-21 23:20:41

当然它返回true,因为孩子是父母的一个实例

ofcourse it returns true because child is an instance of the parent

彡翼 2024-11-21 23:20:41

。每当引用(instanceof 表达式的左侧)可以转换为ReferenceTypeinstanceof 表达式右侧的类型)时,instanceof 将为 true instanceof 表达式)。对于与其父类相关的子类来说也是如此:

Child child = new Child();
Parent parent = (Parent) child; //works!
assert child instanceof Parent; //true

来自 Java 语言规范,Java SE 9 版

15.20。关系运算符
...
RelationalExpression实例ReferenceType

15.20.2。类型比较运算符instanceof
...
在运行时,如果 RelationalExpression 的值不为 null 并且可以将引用强制转换为ReferenceType,而不会引发ClassCastException。否则结果为false

Yes. instanceof will be true whenever the reference(left side of the instanceof expression) can be cast to the ReferenceType(the type on the right side of the instanceof expression). This will be true for subclasses in relation to their parent:

Child child = new Child();
Parent parent = (Parent) child; //works!
assert child instanceof Parent; //true

From The Java Language Specification, Java SE 9 Edition:

15.20. Relational Operators
...
RelationalExpression instanceof ReferenceType

15.20.2. Type Comparison Operator instanceof
...
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文