I am interested in learning OOPs concepts. While trying a simple program using Inheritance. I have noticed this error. I can't understand why this error occur? I have given that simple c# code below:
class Animal
{
public void Body()
{
Console.WriteLine("Animal");
}
}
class Dog : Animal
{
public void Activity()
{
Console.WriteLine("Dog Activity");
}
}
class Pomeranian : Dog
{
static void Main(string[] args)
{
//Dog D = new Dog();
Dog D = new Pomeranian(); -----> No error occur at this line
Pomeranian P = new Dog(); -----> Error occur at this line
D.Body();
D.Activity();
Console.ReadLine();
}
}
Any one please tell me what is actually happening there...
You have to understand the concept Every Dog is an Animal, but not all Animals are Dogs.
Program
is a terrible name, let's get rid of that and make it Pomeranian
: now everthing will be clear.
Pomeranian P = new Dog();//This is not valid because not all dogs are Pomeranian.
but you can do the following
Dog d = new Pomeranian();//You know why this works :)
I hope this helps.
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