在祖父母 class 上使用 instanceof 将 class 抽象为 non-abstract children classes

Using instanceof on granparent class to abstract class with non-abstract children classes

我的代码有问题。我有一个 grandparent class,一个摘要 parent class non-abstract children

public class GrandParent () {
// codes here
}


public abstract class Parent1 extends GrandParent () {
// codes here
}

public class A extends Parent1 () {
// codes here
}

public class B extends Parent1 () {
// codes here
}

我还有一个 class,我把所有东西都放在那里。我创建了一个 grandparent class 的数组列表,其中包含 parent class 的 children。当我尝试使用 instanceof 时,它给了我一个错误,我不明白为什么。 parent class 是granparent 的subclass 但是为什么会出错?

public class Main () {
    ArrayList <GrandParent> gps;

    public Main () {
       gps = new ArrayList<> ();

       gps.add(new A());
       gps.add(new B());

    }

    public void method () {
       if(gps.get(0) instanceof Parent1) {   // in here i get an error that says inconvertible types; cannot cast GrandParent to java.util.Parent1
           //codes
       }

看来这里有一些问题。首先classMain中的main方法需要是public static void main (String[] args)。这就是 Java 对 main 方法的期望。那么ArrayList需要是static的,否则定义在class层就无法引用。或者,您可以在 main 方法中定义 gps,然后将其作为参数传递给 method()

另请注意,您将 () 放在 class 的名称后面。那是不正确的。只有方法应该有参数列表。

现在代码处于可以修复任何其他问题的状态。请记住,instanceof 应该能够转换为父类型来进行检查。父类型是否抽象并不重要。这不相关。所以没有理由不能检查 AB 是否属于 Parent1 类型。 Parent1 是否抽象并不重要。为了证明这一点,请看下面的小例子。

public class Main {

        public static void main (String [] args) 
        {
            GrandParent baz = new A();
            GrandParent biz = new B();

            if (baz instanceof Parent1)
               System.out.println("hi");

            if (biz instanceof Parent1)
               System.out.println("hi again");
        }
}

如果你运行这个,没有错误并且输出"hi"和"hi again"都被打印出来。这类似于代码中发生的情况,因为 ArrayList gps 中的元素是 GrandParent 对类型 AB 对象的引用。

这是应用了更正后的代码。请注意,每个 class 都在其自己的文件中,因为它们都是 public classes:

import java.util.ArrayList;

class GrandParent {
// codes here
}


abstract class Parent1 extends GrandParent {
// codes here
}

class A extends Parent1 {
// codes here
}

class B extends Parent1 {
// codes here
}



public class Main {

    public static ArrayList<GrandParent> gps;

    public static void main (String [] args) {
       gps = new ArrayList<>();    

       gps.add(new A());
       gps.add(new B());


    }

    public static void method () {
       if(gps.get(0) instanceof Parent1) {   // in here i get an error that says inconvertible types; cannot cast GrandParent to java.util.Parent1
           {
             //Codes here 
           }

       }
    }
}

但是还有一件事。从软件设计的角度来看,让你的代码依赖于类型检查并不是一个好主意。换句话说,您的程序的行为不应依赖于像这样显式检查类型。最好在 class 本身中定义该行为。例如,您可以覆盖子 classes 中的方法来定义与其祖先不同的行为。同样,您可以在 class 中提供接口的实现。请注意,这两种方法都不需要显式类型检查。