Search code examples
javaarraysinstanceof

using instanceof to check if an arrayelement belongs to a certain class


So I made two classes.

  1. Rectangle
  2. coloredRectangled extends Rectangle

Than I made an array of Rectangles and inserted this check:

if(tabel[i] instanceof coloredRectangle){}

Netbeans tells me 'inconvertible types ,requiered coloredRectangle ,found Rectangle' I thought that with polymorphism it could work. What am i doing wrong?

Code Rectangle:

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();
    }
}

// faulty code is in the following method - Rechthoek = Rectangle and kleurRechthoek = coloredRectangle

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

Solution

  • That's because you (probably) cannot cast from tabel[i] to coloredRectangle.

    It's stated in the JLS that instanceof will cause compilation problems if the above occurs:

    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.