Method Overriding in C# and Java

Recently I have been trying to learn C#. As a long-time Java developer, there have been a few surprises. C# and Java have a lot in common, so it’s hard for me to notice some of the subtle differences. Today, for instance, I found out that method overriding in C# takes extra effort. In Java, you define methods and then override them in subclasses by simply declaring a method with the same name and arguments. That is not the case in C#, but it took me a while to figure out why the Java code I was converting to C# was not working correctly.

With C#, you have to add the “virtual” keyword to any method you intend to override. In subclasses, you have to add the “override” keyword. This is illustrated below for a “makeMove” method for the game of Gomoku.

public class GomokuPlayer
 ...

public virtual Move makeMove (State gstate, int whichPlayer) {
    ...
    return someMove;
 }
 ...
}
public class FastPlayer : GomokuPlayer {
 ...
 public override Move makeMove (State gstate, int whichPlayer) {
    ...
    return myMove;
 }
 ...
}

C# virtual and override are well explained here: http://www.codeproject.com/Articles/18734/Method-Overriding-in-C

About Bill Lahti

Bill Lahti is a software engineer building mobile applications and knowledge management solutions. Two of his interests are writing for this blog and building Android apps, with strategy games being an area of particular interest.
This entry was posted in Java and tagged , . Bookmark the permalink.

One Response to Method Overriding in C# and Java

  1. it’s all about the ” virtual ” word 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s