From 714ca799d7d293664e8b258f4f97002a05024936 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Mon, 9 Aug 2021 23:22:07 +1000 Subject: [PATCH] 3.2.1 Polymorphism --- chap03.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/chap03.md b/chap03.md index d36657d..169182b 100644 --- a/chap03.md +++ b/chap03.md @@ -407,6 +407,24 @@ House mansion = new House { Name = "Mansion", ### 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.3 Virtual Function Members