Why this difference of handling method ambiguity in Java & c#?

In Java, methods are virtual by default.
In C#, methods are not virtual by default.

So, in order for the C# code to behave the same as the Java code, make the method virtual in the base class and override in the derived class.

Or, in order for the Java code to behave the same as the C# code, make the method final in the base class.


In case of c# you need to make the parent method as virtual and child method as an override

class A
{
public virtual void print()
{
System.Console.WriteLine("Inside Parent");
}
}
class B : A
{
public override void print()
{
System.Console.WriteLine("Inside Child");
}
}
class Program
{
public static void Main(string[] args)
{
B b1=new B();
b1.print();
A a1=new B();
a1.print();
System.Console.Read();
}
}

This line:

  A a1=new B();

I think here, in C# you have an example of method hiding. Perhaps you need to explicitly declare the method as overridden (for example in java using the @Override annotation).

Tags:

C#

Java

Oop