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 an indie game developer. Latest project: an exploration game. Recent game: Hop, Skip, and Thump, a simple abstract strategy game. Other iOS and Android games: Double Star II, Wing Leader, Gomoku League.
This entry was posted in Java and tagged , . Bookmark the permalink.

1 Response to Method Overriding in C# and Java

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

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.