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?
No, it’s not a type issue. In C#, to override a method of the parent class requires that you specify the modifier “override”. So, class B should look like this (note the “override” before “String Method()”:
public class B extends A
{
public override String Method()
{
return “this is B”;
}
}
The reason for this difference is that the designer(s) of C# wanted polymorphism to be more explicit (I believe).
Oops sorry, I hijacked the Java example. Here’s what I really wanted to do (using the C# example):
public class B : A
{
public override String Method()
{
return “this is B”;
}
}
Sorry, this is turning into a spam fest… In class A you would also need to mark the Method() as virtual (abstract requires no code and you have code).
I know this seems like overkill. You can read up on some of the reasoning here:
http://codeword.blogspot.com/2003/12/polymorphism-c-vs-java-vs-c.html