I have two classes A & B, where B is derived from A.
Both the classes have a method with same signature. They are called in the following manner in Java & c#-->
In case of JAVA :
class A
{
public void print()
{
System.out.println("Inside Parent");
}
}
class B extends A
{
public void print()
{
System.out.println("Inside Child");
}
}
class test4
{
public static void main(String args[])
{
B b1=new B();
b1.print();
A a1=new B();
a1.print();
}
}
This program generates the following output:-
Inside Child
Inside Child
In case of C# :
class A
{
public void print()
{
System.Console.WriteLine("Inside Parent");
}
}
class B : A
{
public 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 program generates the following output:-
Inside Child
Inside Parent
Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading. In this case, Java uses the type difference to determine which overloaded method to call.
The ambiguities are those issues that are not defined clearly in the Java language specification. The different results produced by different compilers on several example programs support our observations.
There are ambiguities while using variable arguments in Java. This happens because two methods can definitely be valid enough to be called by data values. Due to this, the compiler doesn't have the knowledge as to which method to call.
This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With