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.
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.
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.
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.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With