@Bon Espresso almost said the correct answer, in my opinion. And here is my little addition to it:
You need to understand what exactly it actually does, so the definition:
instanceof is a binary statement that checks if an instance has a specific type
So when you do this:
Map m = new HashMap();
At the time of compilation, m is actually an interface , but the actual test against instanceof occurs at run time with an NOT interface instance , so the compiler cannot be sure if the instance is behind m (some class that implements this interface) is actually a class that can extend date.
I mean, you might have a class with this declaration:
class MyClass extends Date implements Map{ ..... }
And you could do this:
Map myMap = new MyClass(); (myMap instanceof Date)
and that would be perfectly legal, because MyClass actually extends Date.
The idea here, as you can see, is that if it is likely that validation with the instance will succeed, the compiler will not complain.
On the other hand, in the second example:
HashMap m = new HashMap();
You declare the actual implementation of the map interface or instance . In this case, the compiler is sure that the HashMap is not expanding the date, which gives you an error.
Eugene
source share