// illustrating options in inheritance, dynamic dispatch in C# using System; interface I { void f(); } class A : I { public int x; public A(int y) {x=y;} public void f() { Console.WriteLine("A.f:"+x); } public void g() { Console.WriteLine("A.g"); } public virtual void h() { Console.WriteLine("A.h"); } } class B: A { public new int x=2; // note new public B(int y) : base(y) // superclass is called "base" class { x = 2; } // inherits f : which x will x print? dynamic dispatch on variables? no. public new void g() { Console.WriteLine("B.g"); } public override void h() { Console.WriteLine("B.h"); } } public class inheritnew { public static void Main() { I b = new B(1); // b has static type I, dynamic type B b.f(); // which x will it print? (A.x) // b.g(); compiler error because I does not contain g. ((B)b).g(); // print B.g A n; // n has static type A Console.Write("Enter A or B: "); char x = (char)Console.Read(); if (x=='A') n = new A(1); else n = new B(1); // what is the dynamic type of n? // assume 'B' was entered n.g(); // prints A.g n.h(); // prints B.g // only here did dynamic dispatch occur // is there anywhere else that dynamic dispatch occurs? test2(); // see below }//Main static void F(object x) { Console.WriteLine("F: "+x); } static void G(string x) { Console.WriteLine("G(string)"); } static void G(object x) { Console.WriteLine("G(object)"); } // is overloading the same as dynamic dispatch? static void test2() { object x = "abc"; // perfectly valid: strings ARE objects F("xyz"); // will this work? yes, compiler knows strings are objects G(x); // x has static type object, dynamic type string, so which G? // answer: G(object) will be called: NO DYNAMIC DISPATCH HERE! // Same behavior in java. } }//inheritnew /* Conclusion: dynamic dispatch only occurs in C# with the words virtual and override, which only works on methods and not on instance variables. Dynamic dispatch also does not occur with arguments to functions or methods (static or instance methods). Overloading a function name by the type of its arugments is resolved at compile time, not at runtime. */