8

Me and my friend, who is a Java programmer, were discussing inheritance. The conversation almost reached the heights when we got different results for same kind of code. My code in .NET:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();

            Console.ReadLine();
        }
    }

    public class Base
    {
        public virtual void Show()
        {
            Console.WriteLine("Show From Base Class.");
        }
    }

    public class Derived : Base
    {
        public void Show()
        {
            Console.WriteLine("Show From Derived Class.");
        }
    }
}

Gives me this result:

Show From Base Class.

While the code this code in Java

public class Base {
    public void show() {
        System.out.println("From Base");
    }
}

public class Derived extends Base {
    public void show() {
        System.out.println("From Derived");
    }

    public static void main(String args[]) {
        Base obj = new Derived();
        obj.show();
    }
}

Gives me this result:

From Derived

Why is .NET calling the Base class function and java calling derived class function? I will really appreciate if someone can answer this or just provide a link where I can clear this confusion.

I hope there is nothing wrong with the code provided.

nobody
  • 19,814
  • 17
  • 56
  • 77
Jas
  • 419
  • 1
  • 6
  • 14

2 Answers2

8

The difference is you "hide" Show method in C# version when you "override" it in Java.

To get the same behavior:

public class Derived : Base
{
    public override void Show()
    {
        Console.WriteLine("Show From Derived Class.");
    }
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

In java every method is virtual by default and there is no need to mark a method as overriden. Where as in C# you must specify the virtual and override keywords otherwise it is effectively a new method. You will get a warning, and should either choose the new or override keyword to hide this warning.

Note: Java has an attribute you can use, @Override, but it's use is optional.

weston
  • 54,145
  • 21
  • 145
  • 203