Question

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;
        }
    }
}
Était-ce utile?

La 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.

Autres conseils

Read about instanceof operator here.

Change

if(kleurRechthoek instanceof tabel[i] ){

to

if(tabel[i] instanceof kleurRechthoek){

Now that you have edited the question, see ᴍaroun ᴍaroun answer.

Assuming kleurRechthoek is a class (I would suggest having all class names start with a capital letter), then you are using the instanceof operator incorrectly. It should be used

OBJECT instanceof CLASS_NAME

so for example

new Double(1d) instanceof Number // == true
Double instanceof Number // invalid use, left-hand operator must be an object
Double.class instanceof Number // the compiler will complain here about "Incompatible conditional operand types Class<Double> and Number" since the instanceof check will always return false. However if you do something like : 
((Object) Double.class) instanceof Number // == false
Double.class instanceof Class // == true
Double.class instanceof Class.class // invalid use, right-hand operand must be a class name not an instance of that class object

in your case you want to do something like

tabel[i] instanceof kleurRechthoek
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top