Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in inheritance in C# and Java [duplicate]

Me and my friend, who is a Java programmer, were discussing inheritance. The conversation almost reached the heights when we got different results for same kind of code. My code in .NET:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();

            Console.ReadLine();
        }
    }

    public class Base
    {
        public virtual void Show()
        {
            Console.WriteLine("Show From Base Class.");
        }
    }

    public class Derived : Base
    {
        public void Show()
        {
            Console.WriteLine("Show From Derived Class.");
        }
    }
}

Gives me this result:

Show From Base Class.

While the code this code in Java

public class Base {
    public void show() {
        System.out.println("From Base");
    }
}

public class Derived extends Base {
    public void show() {
        System.out.println("From Derived");
    }

    public static void main(String args[]) {
        Base obj = new Derived();
        obj.show();
    }
}

Gives me this result:

From Derived

Why is .NET calling the Base class function and java calling derived class function? I will really appreciate if someone can answer this or just provide a link where I can clear this confusion.

I hope there is nothing wrong with the code provided.

like image 866
Jas Avatar asked Apr 25 '14 17:04

Jas


People also ask

What is difference between inheritance?

Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms.

What is the difference between multiple inheritance?

Definition. Single inheritance is a type of inheritance that enables a derived class to inherit attributes and methods from a single parent class while multiple inheritance is a type of inheritance that enables a derived class to inherit attributes and methods from more than one parent class.


1 Answers

The difference is you "hide" Show method in C# version when you "override" it in Java.

To get the same behavior:

public class Derived : Base
{
    public override void Show()
    {
        Console.WriteLine("Show From Derived Class.");
    }
}
like image 155
Alexei Levenkov Avatar answered Oct 12 '22 09:10

Alexei Levenkov