Java – inheritance and ‘instanceof’ test results
•
Java
I'm studying 'instanceof' Java, but I can't clearly understand 'instanceof'. I think the following answers are true and false, but the results are true Can you explain why this result occurs? As far as I know, when a is the child of B (parents), the example of B is' false ', but the result is different from my idea
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); } }
Solution
Manifesto= value
You declare your car as a car, but the value is fireengine
Instanceof works based on values, not variable declarations!!!
Shortening may help to understand:
System.out.println(new FireEngine() instanceof FireEngine); // true System.out.println(new FireEngine() instanceof Car); // true
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码