I am quite new to C#, so i hope if my question sounds silly please pardon my ignorance.
- I was trying out Inheritance
funda with C#
and find it to behave in some odd manner, so i thought to check it out with Java
, and i got my expected result.
- I just want to know is there anything i am missing here.......
C# CODE :
class Animal
{
public void Sound()
{
System.Console.WriteLine("I don't make any sound");
}
}
class Dog : Animal
{
public void Sound()
{
System.Console.WriteLine("barking");
}
}
class InheritTest
{
static void Main()
{
Animal a = new Dog(); // Implicit conversion
Dog d = (Dog) a; // Explicit conversion
a.Sound();
d.Sound();
}
}
OUTPUT :
I don't make any sound
barking
JAVA CODE :
class Animal
{
public void sound()
{
System.out.println("I don't make any sound");
}
}
class Dog extends Animal
{
public void sound()
{
System.out.println("barking");
}
}
class InheritTest
{
public static void main(String[] args)
{
Animal a = new Dog(); // Implicit conversion
Dog d = (Dog) a; // Explicit conversion
a.sound();
d.sound();
}
}
OUTPUT :
barking
barking
- Now my doubt about this whole episode is.. In C#
i am assigning Dog object
into the Object Reference Variable a
of type Animal
, then when i call method Sound()
on a
, i should be getting the output as barking
(which is the overridden method in Dog class )but instead Animal's Sound()
method is called giving the output as I don't make any sound
.
- But in Java
things are working as expected.. Inheritance works the same way anywhere, so where did i go wrong.
I will be obliged if someone can help me out with it...... Thanks in advance.
In your first example, you're not actually overriding existing method — you're hiding it. It is a special C# mechanism, which is different from traditional method overriding. Mark the source method as virtual
and override method as override
for it to work as you expect. Here's a good explanation. Didn't you get a warning about that?