What is the concept of creating class instance using interface name?

后端 未结 3 1632
难免孤独
难免孤独 2021-01-14 23:46

what is the concept of set variable or object or i don\'t know what it\'s called when i create instance of class and putting in left hand the name of interface,,, I Know tha

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 00:20

    concept is simple:

    public class Cat : IAnimal {
         public void Voice() {//implements IAnimal's method
             Console.WriteLine("Miyaoo");
         }
    }
    
    public class Dog: IAnimal {
         public void Voice() {  //implements IAnimal's method
             Console.WriteLine("Woof");
         }
    }
    
    public interface IAnimal {
          public void Voice();
    }
    

    after initialization

    IAnimal animal1 = new Cat(); 
    IAnimal animal2 = new Dog(); 
    

    and somewhere in the code

    public void MakeAnimalSound(IAnimal animal) {
       animal.Voice(); 
    }
    

    so you can do something like this:

    MakeAnimalSound(animal1); //prints "Mew" even if type is IAnimal
    MakeAnimalSound(animal2); //prints "Woof" even if type is IAnimal
    

    This is polymorphism.

提交回复
热议问题