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

后端 未结 3 1633
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2021-01-15 00:21

    What happens exactly is that you are creating an instance of the specific class, then you are upcasting the reference to the type of the interface.

    The type of the reference defines what you can access in the instance. You can only use members of the class that the interface knows about.

    The actual type of the object is still the type of the instance that you created, so you can downcast the reference to that type again:

    SqlDataReader reader = (SqlDataReader)oSQLReader;
    
    0 讨论(0)
  • 2021-01-15 00:22

    The concept here is to accomplish the design principle "Program to an interface, not to implementation".

    Here the interface can be an abstract class or the actual interface. The concrete class will have the actual implementation which are being exposed to outside world through interfaces. The client code will access the functionality using interface ,preventing them to directly create an object of concrete class, just giving them access through interface object.

    This is accomplished by OO design patterns I believe.

    0 讨论(0)
提交回复
热议问题