java - 使用instanceof检查数组元素是否属于某个类

标签 java arrays instanceof

所以我做了两个类。

  1. 矩形
  2. coloredRectangle 扩展了 Rectangle

然后我制作了一个矩形数组并插入了此检查:

if(tabel[i] instanceof coloredRectangle){}

Netbeans 告诉我“不可转换的类型,需要有色矩形,找到矩形” 我认为通过多态性它可以工作。我做错了什么?

代码矩形:

public class Rechthoek implements Printbaar {
protected double lengte,breedte;
private Rechthoek[] tabel;

public Rechthoek(int lengte,int breedte){
    this.lengte=lengte;
    this.breedte=breedte;
}

public String getInfo(){
    return ("De lengte van de rechthoek is "+lengte+" en de breedte is "+breedte+" .");
}

public void schrijfTabel(Rechthoek[] tabel){
    for (int i = 0; i < tabel.length; i++) {
        tabel[i].getInfo();
    }
}

//错误代码在以下方法中 - Rechthoek = Rectangle 和 kleurRechthoek = ColoredRectangle

public boolean bevatKleur(Rechthoek[] tabel,String kleur){
    for (int i = 0; i < tabel.length; i++) {
        if(tabel[i] instanceof kleurRechthoek ){
            return true;
        }
    }
}

最佳答案

那是因为您(可能)无法从 tabel[i] 转换为 coloredRectangle

JLS 中有说明如果发生上述情况,instanceof 将导致编译问题:

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

关于java - 使用instanceof检查数组元素是否属于某个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21407463/

相关文章:

Java:如何使用 CMYK 图像?

java - 通过 ProcessBuilder 的 Shell 命令无法在 MacOS 上执行任何操作,但退出代码 == 0 并且没有错误

java - 我可以将数组作为参数传递给 Java 中具有可变参数的方法吗?

java - 从大小为 N 的数组生成一组 M 个元素的概率

ios - UserDefaults 和 If/else 不稳定的行为

java - if 语句中的多个 instanceof

java - 多态性和混淆实例

java - S3 java API 未正确列出文件夹。

java - 使用android登录网站

java - 调用对象的方法,即接口(interface)的实例