1) Why does the following codes differ.
C#:
class Base
{
public void foo()
{
System.Console.WriteLine("base");
}
}
class Derived : Base
{
static void Main(string[] args)
{
Base b = new Base();
b.foo();
b = new Derived();
b.foo();
}
public new void foo()
{
System.Console.WriteLine("derived");
}
}
Java:
class Base {
public void foo() {
System.out.println("Base");
}
}
class Derived extends Base {
public void foo() {
System.out.println("Derived");
}
public static void main(String []s) {
Base b = new Base();
b.foo();
b = new Derived();
b.foo();
}
}
2) When migrating from one language to another what are the things we need to ensure for smooth transition.
The reason is that in Java, methods are
virtualby default. In C#, virtual methods must explicitly be marked as such.The following C# code is equivalent to the Java code – note the use of
virtualin the base class andoverridein the derived class:The C# code you posted hides the method
fooin the classDerived. This is something you normally don’t want to do, because it will cause problems with inheritance.Using the classes you posted, the following code will output different things, although it’s always the same instance:
The fixed code I provided above will output “derived” in both cases.