Questions about "casting operation" in OOP
- by rhapsodyn
When programming, we usually use some type-casting operations.
When the casting happens on the objects "on the same level", it feels ok. But when it happens on the ojects "on the different levels"(mainly between father and son), it feels weird.
Considering this:
Class Son extends Father
WhenSon s = (Son)father;, it's absolutely unreasonable. Because a "Son" is not a "Father" anymore, "Son" may grow up with some new properties "Father" doesn't have, the casting operation makes these properties unknown.
On the other hand, Father f = (Father)son seems reasonable, but according to LSP
"An instance of a derived should be able to replace any instance of its superclass"
A "Son" can do anything his "Father" can, so the casting operation seems useless.
So can i say that these casting operations are agaisnt OO design principle but necessary?