Madhawa Learns To Blog : C#, Java

.net, c#, java,sql, OOAD and more mad memory dumps...

  Home  |   Contact  |   Syndication    |   Login
  47 Posts | 0 Stories | 57 Comments | 15 Trackbacks

News

Archives

Post Categories

Blog Roll

Hang Outs

My old blog

Have you ever wondered why instance methods in java are virtual by default and in C# not? In C# to make a method virtual you have to explicitly do it right? Why is that?

I think better to ask from creator of the C# language. :)

So this is what Anders Hejlsberg says:

There are several reasons. One is performance. We can observe that as people write code in Java, they forget to mark their methods final. Therefore, those methods are virtual. Because they're virtual, they don't perform as well. There's just performance overhead associated with being a virtual method. That's one issue.

A more important issue is versioning. There are two schools of thought about virtual methods. The academic school of thought says, "Everything should be virtual, because I might want to override it someday." The pragmatic school of thought, which comes from building real applications that run in the real world, says, "We've got to be real careful about what we make virtual."

When we make something virtual in a platform, we're making an awful lot of promises about how it evolves in the future. For a non-virtual method, we promise that when you call this method, x and y will happen. When we publish a virtual method in an API, we not only promise that when you call this method, x and y will happen. We also promise that when you override this method, we will call it in this particular sequence with regard to these other ones and the state will be in this and that invariant.

Every time you say virtual in an API, you are creating a call back hook. As an OS or API framework designer, you've got to be real careful about that. You don't want users overriding and hooking at any arbitrary point in an API, because you cannot necessarily make those promises. And people may not fully understand the promises they are making when they make something virtual. more...

posted on Sunday, September 17, 2006 10:38 PM

Feedback

# re: Why instance methods in java are virtual by default and in C# not? 9/15/2011 1:53 AM Niket Chandane
Nice Article...

Post A Comment
Title:
Name:
Email:
Comment:
Verification: