I came across an interesting one (it works in both Java and C #). Java Code:
public class TestStuff { public static void main(String[] args) { Printer p = new PrinterImpl(); p.genericPrint(new B()); } } class PrinterImpl implements Printer { void print(A a) { System.out.println("a"); } void print(B b) { System.out.println("b"); } @Override public <T extends A> void genericPrint(T b) { print(b); } } interface Printer { public <T extends A> void genericPrint(T a); } class A { } class B extends A{ }
C # code:
namespace TestStuff { internal class Program { private static void Main(string[] args) { var printer = new Printer(); printer.GenericPrint(new B()); } } public class Printer { public void Print(A a) { Console.WriteLine("a"); } public void Print(B b) { Console.WriteLine("b"); } public void GenericPrint<T>(T a) where T : A { Print(a); } } public class B : A { } public class A { } }
When I wrote something like this, I expected to see a "b" printed in both cases. But, as you can see, this is the "a" that is printed.
I read the C # language specification and it says that an overloaded method was selected at compile time. This explains why it works that way.
However, I did not have time to check this in the Java language specification.
Can someone please give a more detailed explanation of what is happening and why? And how could I achieve what I wanted?
Thanks in advance!
source share