The biggest problem is not finding one of the problems: talk about abusing inheritance

There is such a use case.

People{

}

 

Man extends People{

}

 

Woman extends People{

}

 

WorkingMan extends Man {

}

 

WorkingWoman extends Woman{

}

 

Here comes the problem, now to add an engineer and a manager, you need to write four classes

EngineerMan extends WorkingMan{

}

 

EngineerWoman extends WorkingWoman{

}

 

ManagerMan extends WorkingMan{

}

ManagerWoman extends WorkingWoman{

}

 

Now that there are robots, how to expand? ManagerRobot,

 EngineerRobot, Robot, ChefRobot?

 

 

Now there is a new profession, engineer manager, how to write?

 

Write at least three classes

 

EngManager extends ManagerRobot

EngManager extends ManagerMan

EngManager extends ManagerWoman

 

Worse yet, we can't reuse the code described by the profession of Engineer, and all engineers have to be rewritten?

 

Many people don't think they're so stupid, but that's actually what they do. When you use the extends tag every time, you won't find anything wrong. Be aware that the class in the example above may not have been written by one person.

In reality, it is impossible for him to complete it alone. Once he is allowed to complete it alone, he will definitely feel very tired and will not write like this.

 

Similar in android:

 

View inherits n levels

Activity inherits n levels

Fragment inherits n levels

 

and custom

Event inherits n levels.

 

Once there are more than three levels of inheritance, the code becomes difficult to understand and maintain. Thinking in java hopes that we use inheritance as little as possible, but less use does not mean no use, so how can we do it better?

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326489463&siteId=291194637