开发者

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

In Java, the method call of an o开发者_运维技巧bject 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?


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.


In Java all non-static methods are virtual, however for the static methods, the type of the reference is all that matters. For this reason it is considered bad practice to use a reference for a non-virtual static method and using the class instead is preferred.

e.g. you can write

Integer i = null;
int j = i.parseInt("1");

This won't throw an exception because not only is actual type of i ignored but so is its value.

It is extremely rare that you would want to call a parent's method instead of the child's method. The developer of the child class overrode the method for a reason. Having to imagine how your class would behave if any combination of overridden methods could be un-overriden is a headache I would rather do without.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜