Can somebody please clear my dought once and for all.
Line 3 generates a compiler error. Ok. But why doesn't line 4 generate one? The references are of different types... And juding by K&B, they are not from the same class heirechy (which again, should cause a compile-time error).
The compile time error you're seeing on line 3 only happens when you are comparing two concrete class references from different inheritance hierarchies. In other words, the compiler knows from the reference type alone that it's impossible for those two references to be referencing the same object because it's impossible for them to be the same class.
Line 4 compiles without a problem because one of the variables is an interface reference (myCol), so the compiler cannot be sure what kind of object that variable references. Here's an example of your program with some more interfaces and classes being compared:
So when you compare a reference variable of an interface type to any other reference variable at all, the compiler will not generate an error.
The reason is that compiler does not know what the actual object type is for a reference variable. It only knows what the reference type is. If either of the reference types is an interface, then it is possible for the two reference variables to be equal. For example, you could make this class:
Note that SubTreeMap IS-A TreeMap and also that SubTreeMap IS-A Collection.
Then in your main method you could put:
Then if you were to compare (myMap==myCol) the result would be true, because the same SubTreeMap object is referenced by both variables.