简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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