#346 - Polymorphism

Recall that polymorphism is one of the three core principles of object-oriented programming.

Polymorphism is the idea that the same code can act differently, depending on the underlying type of the object being acted upon. The type of the object is determined at run-time, rather than at compile-time.

In C#, you can use a variable declared as a base type to refer to instances of one or more derived types. Polymorphism allows you to call a method that exist in the base type but whose implementation exists in the derived types. The appropriate method in the derived type will be called, based on the type of the object.

1 Dog d;

2 

3 d = new Terrier("Jack", 15);

4 d.Bark();    // Terrier.Bark is called

5 

6 d = new Shepherd("kirby", 12);

7 d.Bark();    // Shepherd.Bark is called

 原文地址:#346 - Polymorphism

你可能感兴趣的:(Polymorphism)