Search code examples
c#javaprogramming-languagesbindinglanguage-design

What is the explanation behind a significant difference in the way Java and C# handle method binding?


In Java, the method call of an object depends solely on the object type, and not the reference type.

In C#, the reference type plays an important role in determining whether the method from the parent class is called or the method from the child class is called, based on whether the method is virtual or not.

  1. Is the above statement accurate?
  2. Why does Java restrict this, and does it not take away some power from the programmer?

Solution

  • Your definition is incorrect. In C# it is not based just on whether method is virtual. Even virtual methods can behave differently based on type of reference. See example below and watch at keyword new.

    Java language is simple. It tries to stay simple. Yes, it does take away "some power" as you wrote, but in compensation you get clean code easy to understand.

    C# language has more features, but sometimes you need to try hard to understand all of them. This particular example on inheritance of methods with same name is a nice example. We can create more interesting things in C#.... which nobody will understand.

    Usually we cannot choose language because we are constrained by system platform, libraries and other technologies.

    class A {
      public virtual void M1() {
        Console.WriteLine("A.M1()");
      }
    }
    
    class B : A {
      public new virtual void M1() {
        Console.WriteLine("B.M1()");
      }
    }
    
    class Program {
      static void Main(string[] args) {
        B b = new B();
        b.M1();
        A a = b;
        a.M1();
      }
    }
    

    In C# you get two different results, although you have the same object.