Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java and C# differ in oops?

Tags:

java

c#

oop

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.

like image 537
Prince Ashitaka Avatar asked Aug 25 '11 09:08

Prince Ashitaka


1 Answers

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.

like image 146
Daniel Hilgarth Avatar answered Sep 19 '22 12:09

Daniel Hilgarth