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

非 Y 不嫁゛ 提交于 2019-12-01 11:34:54

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;

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!