What is the concept of creating class instance usi

2020-03-29 10:39发布

问题:

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 that we can't create and object of type interface.

Only I need more clarification what this process named or what is the details done by .Net when I declare these type of object.

IDataReader oSQLReader = new SqlDataReader();
IDataReader oOLEReader = new OleDbDataReader();

回答1:

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;


回答2:

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.



回答3:

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.