instanceof operator in java for comparing different classes

前端 未结 4 1298
刺人心
刺人心 2020-12-11 02:57

I was trying to see how instanceof operator in Java works and am facing a very odd issue.

public static void main(String[] args) {
    Map m = new HashMap();         


        
4条回答
  •  囚心锁ツ
    2020-12-11 03:47

    @Bon Espresso almost did say the right answer in my opinion. And here is my small adding to it:

    You have to understand what instanceof really does, thus the definition:

    instanceof is a binary operator that checks if an instance is of a certain type

    So, when you do this:

     Map m = new HashMap();
    

    At compile-time m is actually an interface, but the actual test against instanceof happens at runtime with an instance NOT an interface, thus the compiler can not be sure if the instance "behind" m (some class that implements this interface) is actually a class that could extend Date.

    I mean you could have a class with a Declaration like this:

    class MyClass extends Date implements Map{
         .....
    }
    

    And you could then do this:

     Map myMap = new MyClass();
     (myMap instanceof Date) 
    

    and it would be perfectly legal, because MyClass actually extends Date.

    The idea here as you can see, that if there is the smallest chance that the check with instanceof will succeed, the compiler will not complain.

    On the other hand in your second example:

        HashMap m = new HashMap();
    

    You are declaring an actual implementation of the Map interface, or an instance. In this case the compiler is sure that HashMap does not extend Date, thus giving you the error.

提交回复
热议问题