有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何区分子类?

我有父类和两个子类。 我想在我的方法checkType(List<Parent>)中设置一个条件 我的主课 无论是父母。getClass()返回Child1或Child2 假设我有一个存储所有对象的列表。 所以checkType方法可以计算列表中有多少child1和child2

abstract class Parent
{
...

   public Parent getClass
   {
     ...
   }

}

class Child1 extends Parent
{
...    
}

class Child2 extends Parent
{
... 
}

共 (2) 个答案

  1. # 1 楼答案

    在父类中创建函数checkType()。可以在子类中重写此函数,以指示它是哪个子类。比如

    abstract class Parent {
      public abstract String checkType();
    } 
    public class Child1 extends Parent {
      public String checkType() {
        return "Child 1"
    }
    public class Child2 extends Parent {
      public String checkType() {
        return "Child 2"
    } 
    
  2. # 2 楼答案

    if (obj1 instanceof Child1) {
        System.out.println(Child1.class.toString());
    } else if (obj1 instanceof Child2) {
        System.out.println(Child2.class.toString());
    }