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.

2
  • 3
    You didn't override in csharp. Commented Apr 25, 2014 at 17:37
  • @SotiriosDelimanolis So you mean that in java it is automatically getting override Commented Apr 25, 2014 at 17:40

2 Answers 2

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.");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.