Created
January 2, 2018 12:44
-
-
Save ValerioSevilla/b8eb5dce2831dc95e416956f865eb248 to your computer and use it in GitHub Desktop.
Simple demonstration of how polymorphism through method overriding and hiding works in C# (Unity compatible)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace PolymorphismDemo | |
{ | |
public class A | |
{ | |
public virtual void Foo() { Debug.Log ("A.Foo()"); } | |
} | |
public class B : A | |
{ | |
public new void Foo() { Debug.Log ("B.Foo()"); } // Static binding (hiding) | |
} | |
public class C : A | |
{ | |
public override void Foo() { Debug.Log ("C.Foo()"); } // Dynamic binding (overriding) | |
} | |
/*public class D : A // WARNING: new or override required | |
{ | |
public void Foo() { Debug.Log("D.Foo()"); } | |
}*/ | |
public class E : C | |
{ | |
public sealed override void Foo() { Debug.Log ("E.Foo()"); } // C.Foo() is implicitly virtual | |
} | |
/*public class F : E // ERROR: sealed method cannot be overridden | |
{ | |
public override void Foo() { Debug.Log("F.Foo()"); } | |
}*/ | |
public class G : E | |
{ | |
public new void Foo() { Debug.Log ("G.Foo()"); } // ... but it can be hidden | |
} | |
class MethodOverridingDemo | |
{ | |
static void Test() | |
{ | |
A thing = new A(); | |
B thing2 = new B(); | |
C thing3 = new C(); | |
A thing4 = thing2; | |
A thing5 = thing3; | |
A thing6 = new E(); | |
A thing7 = new G(); | |
thing.Foo(); // A.Foo() | |
thing2.Foo(); // B.Foo() | |
thing3.Foo(); // C.Foo() | |
thing4.Foo(); // A.Foo() | |
thing5.Foo(); // C.Foo() | |
thing6.Foo(); // E.Foo() | |
thing7.Foo(); // E.Foo() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment