Home > Net >  Difference between these objects?
Difference between these objects?

Time:04-18

i have these 2 classes

class Animal
{
    public string name;

    public virtual void MakeSound()
    {
        Console.WriteLine("some sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("bark");
    }
}

id like to know where the differences are between these 2 objects?

Animal dog = new Dog();
Dog dog2 = new Dog();

edit: my problem with this is that i do not understand the process/ thought behind these 2 object. Yes, they both are Dog() object, but what I do not understand WHY i have the possibility to assign Animal AND Dog to the type. I get that "assign" is the wrong wording but what it just seems VERY weird to me that I have the possibility to do that.

Programming has treated me "harshly" until now. Everything has to have the right syntax and everything has to be in the right order and everything hast to make sense. If thats not the case i get an error List<int> list = new List<int>; doesn't work, neither does List<int> list = new List(); nor something else. Thats why I don't get the 2 objects. It seems to me that, functionality wise, they both do and can do the same. But are they actually the same?

CodePudding user response:

As the Animal class is more generic, you can use only for declaration, for instance if you don't know yet what animal is, and change to another subclass as you need. Imagine you have also:

     class Cat: Animal
     {
        public override void MakeSound()
        {
             Console.WriteLine("mew");
        }
      }

You could do:

        Animal animal = new Dog();
        Dog dog2 = new Dog();
        
        animal.MakeSound();
        
        animal = new Cat();
        animal.MakeSound();

And the output is: bark mew

If you only use the Dog class, you have to create another variable for Cat.

I hope this help you.


EDIT

The power can be seen when you make a list or dictionary (or other collection) containing different animals:

var animals = new List<Animal>();
animals.Add(new Dog("Rover"));
animals.Add(new Cat("Tiger"));

foreach (var animal in animals)
{
    Console.WriteLine($"{animal.name} goes:");
    animal.MakeSound();
}

Output:

Rover goes:
bark
Tiger goes:
mew

CodePudding user response:

There is no big difference.

The only real difference is that if you would implement a public method or property in the Dog class which is not in the Animal class, you would not be able to access them unless you cast it like ((Dog)dog).SomeProperty.

Probably the only time you use the Animal class instead of the Dog class is if you need a List containing all the animals.

  • Related