I'm supposed to use an instanceOf for an assignment, and it says the type is incompatible. Here is my code:

package City;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



/**
 *
 * @author Brian
 */
public class City {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here


        Car[] vehicle = new Car[4];
        vehicle[0] = new Car("Ford", 2);
        vehicle[1] = new Limo("Ford", 5, 28);
        vehicle[2] = new SportsCar("Chevy", 3, "Red");
        vehicle[3] = new Roadster("Ford", 3, false);



        for(Car vehicles: vehicle){
            System.out.println(vehicles.toString());

            if(vehicles instanceOf SportsCar){
                System.out.println("Yes");
            }
        }
    }

}

Edited 3 Years Ago by happygeek: fixed formatting

well ... if what you're trying to do is what I think you're trying, you might want to check on the correct spelling of 'instanceOf'.

just changing

if(vehicles instanceOf SportsCar){
System.out.println("Yes");
}

into

if(vehicles instanceof SportsCar){
System.out.println("Yes");
}

might give you just what you want.

You should almost never use instanceof, however. This is generally a sign of a bad design. Do some research on 'Java Design Patterns' and 'Abstraction' to avoid the dreaded instanceof.

This article has been dead for over six months. Start a new discussion instead.