3.2.1 Polymorphism

Jason Zhu 2021-08-09 23:22:07 +10:00
parent 6635f23a7f
commit 714ca799d7

@ -407,6 +407,24 @@ House mansion = new House { Name = "Mansion",
### 3.2.1 Polymorphism ### 3.2.1 Polymorphism
**Polymorphism (多态)**: References (e.g. class) are *polymorphic* (i.e. a variable of type `x` can refer to an object that subclasses `x`)
* As all subclasses have field/properties/methods of superclass, so it's safe
```csharp
// Define a method that try to access superclass
public static void Display (Asset asset)
{
System.Console.WriteLine(asset.Name)
}
// As Stock is subclass of Asset, Display can access it
Stock msft = new Stock ...;
House mansion = new House ...;
Display(msft); // msft is subclass of asset
Display(mansion); // mansion is subclass of asset
```
### 3.2.2 Casting and Reference Conversions ### 3.2.2 Casting and Reference Conversions
### 3.2.3 Virtual Function Members ### 3.2.3 Virtual Function Members