Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and 'Instanceof' testing result

Tags:

java

I'm studying 'instanceof' java, but I couldn't understand 'instanceof' clearly, I thought below answer would be true and false, but result is both true. Could you explain why this result happen? As I know, when A is child of B (Parent), and a instanceof B is 'false' but result is different with what I thought.

class Car{
    String color;
    int door;       
}

class FireEngine extends Car{
    void water(){
        System.out.println("water");
    }
}

public class Operator {
    public static void main(String[] args) {
        Car car = new FireEngine();
        FireEngine fireCar = new FireEngine();

        System.out.println(car instanceof FireEngine);
        System.out.println(fireCar instanceof Car);
    }
}
like image 385
Changil Lee Avatar asked Dec 15 '22 14:12

Changil Lee


1 Answers

Declaration != Value

You declare car as an Car, but the Value is an FireEngine.

instanceof works based on values, not on the declarations of their variables!!!

Shortening may help to understand:

System.out.println(new FireEngine() instanceof FireEngine);  // true
System.out.println(new FireEngine() instanceof Car);         // true
like image 121
Grim Avatar answered Dec 17 '22 04:12

Grim