Questions about "casting operation" in OOP

Posted by rhapsodyn on Stack Overflow See other posts from Stack Overflow or by rhapsodyn
Published on 2010-05-28T05:14:26Z Indexed on 2010/05/28 5:21 UTC
Read the original article Hit count: 214

Filed under:

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?

© Stack Overflow or respective owner

Related posts about oop