开发者

Why does Java and C# differ in oops?

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 f开发者_StackOverflow社区oo() {
    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 virtual by 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 virtual in the base class and override in the derived class:

class Base
{
    public virtual 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 override void foo()
    {
        System.Console.WriteLine("derived");
    }
}

The C# code you posted hides the method foo in the class Derived. 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:

Base b = new Derived();
b.foo(); // writes "base"
((Derived)b).foo(); // writes "derived"

The fixed code I provided above will output "derived" in both cases.


The C# code will compile with warnings, since you are hiding methods there.

In Java, class-methods are always virtual, whereas in C# they're not, and you have to mark them explicitly as 'virtual'.

In C#, you'll have to do this:

public class Base
{
    public virtual void Foo()
    {
        Console.WriteLine ("Base");
    }
}

public class Derived : Base
{
    public override void Foo()
    {
        Console.WriteLine ("Derived.");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜