Archive

Posts Tagged ‘Java’

C# vs Java: casting objects and calling members

February 11th, 2011

Given these two functionally identical code samples in c# and java, what is the output?

C#:

public class A
{
  public String Method()
  {
    return "this is A";
  }
}

public class B : A
{
  public String Method()
  {
    return "this is B";
  }
}

A thisA = new B();

thisA.Method();

Java:

public class A
{
  public String Method()
  {
    return "this is A";
  }
}

public class B extends A
{
  public String Method()
  {
    return "this is B";
  }
}

A thisA = new B();

thisA.Method();

What does thisA.Method() return?

It turns out that there are two different answers to this. In .NET/C# it returns from A (“this is A”). In Java, it returns from B (“this is B”).

So far it appears that this is a type issue; new B() must be getting cast back to A in C#. Looking for some documentation on this specifically. Links anyone?

.NET, Interesting, Technology , ,