title: Java inheritance vs. C# inheritance
body: <p>Let's say Java has these hierarchical classes:</p>
  
  <pre><code>class A 
  {
  }
  class B extends A
  {
      public void m()
      {
          System.out.println("B\n");
      }
  }
  class C extends B
  {
      public void m()
      {
          System.out.println("C\n");
      }
  }
  class D extends C
  {
      public static void main(String[] args)
      {
          A a = new D();
          // a.m(); // doesn't work
          B b = new D();
          b.m();
          C c = new D();
          c.m();
          D d = new D();
          d.m();
      }
  }
  </code></pre>
  
  <p>This is the (blind) duplication of the same code in C#:</p>
  
  <pre><code>using System;
  class A 
  {   
  }
  class B : A
  {
      public void M()
      {
          Console.WriteLine("B");
      }
  }
  class C : B
  {
      public void M() // I need to use public new void M() to avoid the warning
      {
          Console.WriteLine("C");
      }
  }
  class D : C
  {
      public static void Main(String[] args)
      {
          A a = new D();
          // a.M(); // doesn't work       
          B b = new D();
          b.M();
          C c = new D();
          c.M();
          D d = new D();
          d.M();
      }
  }
  </code></pre>
  
  <p>When I execute the Java code, I got <code>C-C-C</code> whereas C# returns <code>B-C-C</code>.</p>
  
  <p>To me C#'s result makes more sense, as reference B invokes its own method.</p>
  
  <ul>
  <li>What's the logic behind the Java designer's decision to print <code>C-C-C</code> instead of <code>B-C-C</code>? I mean, why reference B uses the overriding method in C? What's the advantage of this approach?</li>
  <li>How can I change Java code to print out <code>B-C-C</code> just like C# does? I mean, how can I teach java to invoke the method of the exact reference it uses?</li>
  <li>How can I change C# code to print out <code>C-C-C</code>? I mean, how can I teach C# to invoke the overriding method?</li>
  </ul>