Hello, I have a question, consider the following code:
// Define an interfacepublic interface IAnimal{ void Speak();}// Implement the interface in a classpublic class Dog : IAnimal{ public void Speak() { Console.WriteLine("Woof!"); }}
// Define an interfacepublic interface IAnimal{ void Speak();}// Implement the interface in a classpublic class Dog : IAnimal{ public void Speak() { Console.WriteLine("Woof!"); }}
IAnimal myDog = new Dog(); myDog.Speak(); // Output: Woof!
IAnimal myDog = new Dog(); myDog.Speak(); // Output: Woof!
My question is, an interface is just like an abstract class in the sense that we can' instantiate directly but rather should be instantiated indirectly by using a derived class from it.
When we write:
IAnimal myDog = new Dog();myDog.Speak();
IAnimal myDog = new Dog();myDog.Speak();
I don't understand, we are creating a Dog object, this references a dog? What is the
IAnimal
IAnimal
data type? What does it represents and why not use