我有一个类Child
,延伸Parent
。如果父级的实例返回true,那么instanceof是否会返回true?
Parent child = new Child();
if (child instanceof Parent){
// Do something
}
这是否返回true或false,为什么?
我有一个类Child
,延伸Parent
。如果父级的实例返回true,那么instanceof是否会返回true?
Parent child = new Child();
if (child instanceof Parent){
// Do something
}
这是否返回true或false,为什么?
Yes,它会的。为什么不呢?
因为孩子实际上是父母的一个实例。如果你只想为孩子进行操作,你应该检查
if (child instanceof Child){
}
然而,你应该从有效的C记住下面的语句++,斯科特迈尔斯:
“任何时候你发现自己写 形式的代码“如果对象是 T1类型的,然后做一些事情,但如果 它的类型T2的,然后做一些别的 ,”拍自己。
我认为这也适用于这种情况。如果你想doSomething根据被引用的对象属于什么类型,下面的代码结构应该帮助你。
注意:我还没有编译它。
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() {
Parent p = new Parent();
p.doSomething();
p = new ChildA();
p.doSomething();
p = new ChildB();
p.doSomething();
}
}
的instanceof,如果它是一个子类将返回true ...
ofcourse,因为孩子是家长
是的实例返回true。每当参考(instanceof
表达式的左侧)可以投射到ReferenceType(instanceof
表达式的右侧的类型)时,instanceof
将为真。这将是真正的子类在关系到他们的父母:
Child child = new Child();
Parent parent = (Parent) child; //works!
assert child instanceof Parent; //true
从The Java Language Specification, Java SE 9 Edition:
15.20. Relational Operators
...
RelationalExpression的instanceof 引用类型15.20.2. Type Comparison Operator instanceof
...
在运行时,instanceof
操作的结果是true
如果RelationalExpression的值不null
和参考可强制转换为引用类型没有养ClassCastException
。否则结果是false
。
但我确定运行时的对象类型,我需要定义一个父引用来保存所有类型的子对象。我怎么能以其他方式做到这一点? – ikbal 2011-06-10 09:12:54
@ user479129:您可以在父类型的引用中持有父代的任何子代的引用。也就是说,如果有一个'Parent Parent {}'类和'ChildA extends Parent'和'ChildB extends Parent',那么您可以使用'Parent p'来引用'ChildA'或'ChildB'类型的对象,但是我别相信你的意思。 – 2011-06-10 09:48:24
我需要控制该对象p是它的子类型,而不是父类型。在某些情况下,它可能是父类型,所以我需要检查它是否正是我想要的类型。那是我想要的。我希望它清楚 – ikbal 2011-06-10 11:36:38