Fruit, apples bananas achieve polymorphism

Apple oranges problem, look at the demand: There is not only into the box, there are two apples and bananas fruits, original weight of 50, 30, respectively. Into the box, water loss, reduce weight, reduce 4,3 respectively, until the light is no longer self-3/5.

First of all I would like to sort out the relationship of class

As can be seen, the main function of the box: total weight the day before, the total weight of the number of output apples, oranges quantity output, the output of fruit alleviate the current total weight. Then the user interface, we first need to instantiate a FruitBox objects, methods (AddFruit, PassOneDay, etc.) in the calling object to achieve the function, the focus is on call the method matter, method Fruit class is being used directly, but execution but it is the method of Orange or Apple in, which is the subject of this: polymorphism.

First, we in Fruit is no specific way to implement the method only two empty method, when the subject of specific calls, the derived class (Apple) automatically overrides the base class (Fruit) is to achieve a specific function . The advantage is that when you call only need to call a base class, you can achieve the desired function automatically according to different objects, avoid a lot of duplicate code.

Published 40 original articles · won praise 10 · views 7139

Guess you like

Origin blog.csdn.net/xyzyhs/article/details/98589918