英文:
How to compare the derived objects from a base class in java?
问题
我有一个Base类,从Base类派生出两个类,分别是Derived1和Derived2,我想要检查object是否是Derived1或Derived2类型。
这是我的代码:
public class Base {
int ID;
}
public class Derived1 extends Base {
int subID;
}
public class Derived2 extends Base {
int subID;
}
public class Program() {
public static void main(String []args) {
Base object = new Derived1();
// 我想要检查"object"是否是Derived1或Derived2类型
}
}
英文:
I have a Base class and two classes are derived from the Base class namely Derived1 and Derived2, I want to check whether object is of type Derived1 or Derived2.
This is my code:
public class Base {
int ID;
}
public class Derived1 extends Base {
int subID;
}
public class Derived2 extends Base {
int subID;
}
public class Program(){
public static void main(String []args) {
Base object = new Derived1();
// I want to check whether "object" is of type Derived1 or Derived2
}
}
答案1
得分: 2
object.getClass() == Derived1.class
会返回true。就像object instanceof Derived1
一样。object.getClass().getName()
会返回"com.foo.Derived1"
。Derived1 = (Derived1) object;
要么起作用,要么抛出ClassCastException
。
这些是您的主要三种选择。
英文:
object.getClass() == Derived1.class
would return true. As would object instanceof Derived1
. object.getClass().getName()
would return "com.foo.Derived1"
. Derived1 = (Derived1) object;
would either work, or throw ClassCastException
.
Those are your main 3 options.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论