简体   繁体   English

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

[英]Why does Java and C# differ in oops?

1) Why does the following codes differ. 1)为什么以下代码不同。

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

The reason is that in Java, methods are virtual by default. 原因是在Java中,默认情况下方法是virtual的。 In C#, virtual methods must explicitly be marked as such. 在C#中,必须明确标记虚拟方法。
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: 以下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");
    }
}

The C# code you posted hides the method foo in the class Derived . 您发布的C#代码隐藏了Derived类中的方法foo 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. C#代码将编译并带有警告,因为您在那里隐藏了方法。

In Java, class-methods are always virtual, whereas in C# they're not, and you have to mark them explicitly as 'virtual'. 在Java中,类方法总是虚拟的,而在C#中它们不是,并且你必须将它们显式标记为“虚拟”。

In C#, you'll have to do this: 在C#中,你必须这样做:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM