Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "an explicit conversion exists (are you missing a cast )" comes when creating an object:

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...

like image 714
thevan Avatar asked Dec 08 '22 08:12

thevan


1 Answers

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.

like image 161
Sriram Sakthivel Avatar answered Dec 11 '22 07:12

Sriram Sakthivel