如何在Java中比较来自基类的派生对象?

huangapple go评论69阅读模式
英文:

How to compare the derived objects from a base class in java?

问题

我有一个Base类,从Base类派生出两个类,分别是Derived1Derived2,我想要检查object是否是Derived1Derived2类型。

这是我的代码:

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.

huangapple
  • 本文由 发表于 2020年10月16日 02:11:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64377446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定