19 Jun 2009

This topic is very basic, but I felt like writing something on simple subjects that may be misunderstood. It is also a good excuse to go in language specifications and read all the details that most of the people don't like to read... As I'm working in Java now, I quite like to compare the two languages to see where are the differences and make sure I don't do any silly mistake.

So, when it comes to inheritance, there is a big difference between Java and C#.

Java Inheritance

In a Java subclass, you can override any method of the superclass. The method that is to be called is always determined at run time. So for example, if you write code like this:

public class Parent {
    public String sayHello() {
        return "Hello from Parent";
    }
}

public class Child extends Parent {
    public String sayHello() {
        return "Hello from Child";
    }
}

If you create a new instance of the Child class, when you call the sayHello() method, it is always the Child one that will be called, no matter what the declaration class is. So, you can teat an instance of Child as an instance of Parent, but the methods called will be the ones from Child (if they are overriden, of course).

Code like this:

Parent o = new Child();
System.out.println(o.sayHello());

will output this:

Hello from Child

C# Inheritance

In C#, things are a bit different. C# language needs to be told which method can be overriden (declared as virtual), and which method overrides (declared as override). So to have the same behavior as Java, C# code has to look like this:

class Parent
{
    public virtual String SayHello()
    {
        return "Hello from Parent";
    }
}

class Child : Parent
{
    public override String SayHello()
    {
        return "Hello from Child";
    }
}

If the virtual and override are omitted (or just the override, actually), then it is the Parent's method that is executed when the Child object is declared as Parent.

In C# language specification, there is a clear explanation on how is behaves:

In a virtual method invocation, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a non-virtual method invocation, the compile-time type of the instance is the determining factor.

Summary

To sum it up, in Java the method called will be determined by the instantiation class, while in C# it will depend on how the class and the calling code is written. C# gives you much more flexibility, but it is more complicated and the capacity for a class to override a method is determined by its parent class. With Java, you loose the ability to call the parent's method, but is that very useful? On the other hand, C# ensures that if you don't want a method to be overriden, it won't be.

Oh and we forgot to talk about the new keyword in C#. I never came across code that used it, but a nice description is given here.



blog comments powered by Disqus