// Static v.s. dynamic dispatch in C# using System; class bigobject { protected int x; public bigobject(int x0) { x = x0; } public void f() { Console.WriteLine("super f, x="+x); } public virtual void g() // note 'virtual' { Console.WriteLine("super virtual g, x="+x); } } // bigobject class biggerobject : bigobject { public new int x; // note 'new' public biggerobject(int x0, int x1) : base(x0) { x = x1; } public new void f() { Console.WriteLine("sub f, x="+x); } public override void g() // note 'override' { Console.WriteLine("sub override g, x="+x); } } // biggerobject public class inherit { public static void Main(string[] args) { bigobject A; // static type of A is bigobject, // but dynamic is type unknown at compile time: if (args.Length < 1) A = new bigobject(1); else A = new biggerobject(1,2); A.f(); // calls statically typed f A.g(); // calls dynamically typed g biggerobject B = new biggerobject(2,3); B.f(); // calls static f in class biggerobject B = (biggerobject)A; // compile time ok, but // may cause exception at runtime } } // Java only allows for the dynamic behavior and so the words // "virtual" and "override" are omitted.