为什么Java和C#在oops方面有所不同?

时间:2011-08-25 09:39:05

标签: c# java oop

1)为什么以下代码不同。

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");
  }
}

爪哇:

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)当从一种语言迁移到另一种语言时,我们需要确保顺利过渡。

2 个答案:

答案 0 :(得分:11)

原因是在Java中,默认情况下方法为virtual。在C#中,虚拟方法必须明确标记为这样 以下C#代码等同于Java代码 - 请注意在基类中使用virtual和在派生类中使用override

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");
    }
}

您发布的C#代码隐藏了类foo中的方法Derived。这是你通常不想做的事情,因为它会导致继承问题。

使用您发布的类,以下代码将输出不同的内容,尽管它始终是相同的实例:

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

上面提供的固定代码在两种情况下都会输出“derived”。

答案 1 :(得分:7)

C#代码将编译并带有警告,因为你在那里隐藏了方法。

在Java中,类方法总是虚拟的,而在C#中它们不是,你必须将它们显式标记为“虚拟”。

在C#中,你必须这样做:

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

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