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);
}
}
carhas typeCar, but its value is typeFireEngine. Imagine that the variable is a bottle, a bottle can hold liquids. Beer is a liquid therefore you can put it in a bottle. If you do so,bottle instanceof Beerwill return true, even if the bottle isn't labelled as beer bottle.instanceof, it is 95% of the times a code smell. It is 100% fine to use it for learning purposes and to understand typing and polymorphism, but in the future, when you actually write code, and have to useinstanceof- it should raise a red flag that indicates "something in here is probably poorly designed".