Polymorphism and Casts
Maybe I don't really understand the definition of polymorphism yet, but I'm having a little problem with this: In section "Using Multiple Interfaces" in chapter 6 it says that after you cast a reference to a specific type, you can't get polymorphic behavior anymore.
But what if one introduces a new class, MyClass2 which extends MyClass, then creates an object of that class and stores the reference in the variable ac?
Now the statement on p. 290, ((MyClass)ac).powerOnOff(); would call powerOnOff of MyClass2, despite having casted the reference to MyClass, wouldn't it? Isn't that polymorphic behavior? Also, if one creates an instance of MyClass, stores a reference in ac, and casts to MyClass2? ((MyClass2)ac).powerOnOff(); This would compile just fine, but would result in a runtime error, since the object that ac points to isn't an instance of MyClass2. This doesn't really look like static binding. I'm quite confused, so please help me understand what's wrong here...
|