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

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

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

原因是在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#代码隐藏了Derived类中的方法foo 。 这是您通常不想做的事情,因为它会导致inheritance问题。

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

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

我在上面提供的固定代码将在两种情况下输出“派生”。

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