Questions about "casting operations" in OOP

When programming, we usually use some type casting operations.

When casting happens on objects “on the same level”, it feels good. But when this happens at the objects "at different levels" (mainly between father and son), it seems strange.

Considering this:

Class Son extends Father

When Son s = (Son)father;, this is completely unreasonable. Since the "Son" is no longer the "Father", the "Son" can grow with some new properties that the "Father" does not have, the casting operation makes these properties unknown.

On the other hand, it Father f = (Father)sonseems reasonable, but according to the LSP

"An instance of a derivative must be able to replace any instance of its superclass."

The “Son” can do whatever his “Father” can do, so the casting operation seems futile.

So, can I say that these casting operations are an Oais design principle, but necessary?

+3
source share
5 answers

Object casting in OOP is usually the product of class inheritance or interface inheritance. You should always remember that class inheritance means the relationship is, and interface inheritance means it has a relationship.

Let us turn to your example: it Class Son extends Fatherdoes not sound like a reasonable abstraction, since each male man is a son, but not all of them will be a father. In fact, the opposite may be more applicable: Class Father extends Sonbecause every father is always a son.

, , Class Person, , .. , Person Children.

a Person Father, , Person.Children.Count > 0. , Father .

+2

, , - , :)

. Person

class Person
{
    public bool IsFather { get; set; } // this variable will change depending on the count of children
    public List<Person> children { get; set; }
}

, , .

+2

.

Class Person 
{
    public void walk();
}
Class Man extends Person
{
    public void shaveBeard();
}

- -; "a Man Person".

.

Person p = new Person();
Person m = new Man();

p.walk . shavebeard() m Man. Man; (Man) m.shaveBeard(); , , Man:

if(m instanceof Man)
{
   (Man) m.shaveBeard(); 
}
+1

. :

Son s = (Son)person          //Valid
Father f = (Father)person    //Valid
0

Here's a hint: the class on the left is a superclass, and on the right is a subclass, so if we have this: Object p = new Student (); // true Student s = new Object () // incorrect ... it looks like each object is a student. Care should be taken when performing an explicit cast, as it may look correct, but may not work as expected. You cannot create your own father’s property.

0
source

Source: https://habr.com/ru/post/1747482/


All Articles