Polymorphism

Polymorphism is a fancy word for an important concept: poly = many, morph = shape => many shapes. In our example, we use polymorphism in the association from country to fruit - namely, a resulting list that can contain different subclasses of fruit such as apples, oranges, etc.

Polymorphism allows us to operate on stuff we do not know much about.

Check this out:

Fruit model 2.png

I add a method on Fruit that I make virtual:

Properties 2.png

I can implement this to return a default value on Fruit and override it on the subclasses that should return a different value:

Overrided subclasses fruits.png

1: public partial class Fruit { 
2:     public virtual bool HasSeedsYouNoticeWhenYouEat() 
3:     { 
4:         return true; 
5:     } 
6: }
1: public partial class Banana { 
2:     public override bool HasSeedsYouNoticeWhenYouEat() 
3:     { 
4:         return false; 
5:     } 
6: }

Having this, I write code that goes over a list of Fruit and ask if the fruit HasSeedsThatYouNoticeWhenYouEat like this:

1: List<Fruit> crapfruit = new List<Fruit>(); 
2: List<Fruit> okfruit = new List<Fruit>(); 
3: foreach (Fruit fruit in malaysia.ExportsTheseFruits) 
4: { 
5:     if (fruit.HasSeedsYouNoticeWhenYouEat()) 
6:         crapfruit.Add(fruit); 
7:     else 
8:         okfruit.Add(fruit); 
9: }

If you are still with me, I also want to mention the concept of “Abstract”. When we have a model like the one above, think of the Fruit class as being abstract – meaning that having an instance of a fruit (a real fruit) that is of type Fruit should not be legal. A fruit-instance must be one of the subclasses; it can be an Apple, Pear, Orange, Banana, or Pineapple (in our model) but never just “Fruit.”

In Object Orientation terms, Abstract means that the compiler will treat any attempt to create an instance as an error. It is an error because the developer that defined the class never intended it for direct use; it was designed as an abstraction or generalization of a set of subclasses.

My recommendation is to always treat classes that have subclasses (aka superclasses) as being abstract. In the Fruit sample above, this might be obvious, but remember this when you classify your domain where it might not be so obvious.

The MDriven Book - Next Chapter: Composite and Aggregate and what they imply

This page was edited 43 days ago on 10/02/2024. What links here