0
interface ISpeak
    {
       void Speak();
    }
   class Animal : ISpeak
   {
       public void Speak()
        {
            Console.WriteLine("Animal is speaking. . ."); 
        }
    }
class Program{
 void Main(){
    Animal animal = new Animal();
    Animal.Speak();
}   
} 

And My question:
I create a new obj here: ISpeak animal = new Animal();
And then I call the Speak method: animal.Speak();
The result is the same as the original code, so what is the difference btween ISpeak animal = new Animal(); and Animal animal = new Animal();

  • 1
    The difference is that you can refere to any object implementing the `ISpeak` interface as a `ISpeak`... this is polimorphism one of the pillar of object oriented programmin – Marco Beninca Aug 01 '22 at 09:48
  • And I see someone pass the ISpeak animal = new Animal(); as the parameter for a method like void Speak ( ISpeak animal ). Like this, can I pass Animal animal = new Animal(); as a parameter too ? or only the obj from the class that implements the Ispeak interface – Đỗ Trọng Khoa Aug 01 '22 at 09:52
  • You can do something like `someMethod(new Animal())` where `someMethod` is declared as `void someMethod(ISpeak s)` but in this case after the execution of `someMethod` you'll lose the reference to the new `Animal` object – Marco Beninca Aug 01 '22 at 09:56

0 Answers0