Why are Java and C # different from each other?

1) Why the following codes are different.

WITH#:

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 switching from one language to another, what we need to ensure a smooth transition.

+5
source share
2 answers

The reason is that Java has default methods virtual. In C #, virtual methods should be explicitly marked as such.
The following C # code is equivalent to Java code - note the use virtualin the base class and overridein 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 fooin the class Derived. This is something you usually don't want to do, because it will cause inheritance issues.

, , , :

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

, , "" .

+9

# , .

Java - , # , "".

# :

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

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

All Articles