I found this code which creates an object of the implementation class and assigning it to the interface class variable:
Myinterface obj=new MyImplementationClass();
Why dont we just use
MyImplementationClass obj=new MyImplementationClass();
?
I found this code which creates an object of the implementation class and assigning it to the interface class variable:
Myinterface obj=new MyImplementationClass();
Why dont we just use
MyImplementationClass obj=new MyImplementationClass();
?
There may be more than one class that implements MyInterface. If you use:
MyInterface obj = new MyImplementationClass();
You can also do:
MyInterface obj = new MyOtherImplementationClass();
But if you use the concrete implementation name, you cannot do this (*):
// This wouldn't work:
MyImplementationClass obj = new MyOtherImplementationClass();
And you wouldn't be able to use the following:
MyInterface obj = new MyInterface();
Because you don't know what to insantiate. should it be a MyInterfaceImplementation? Should it be MyOtherInterfaceImplementation?
But there's a technique called Dependency Injection. Which let's you somehow bind a specific implementation to a type. With it, you can do something like the following:
MyInterface obj = dependencyInjectionContainer.Resolve<MyInterface>();
Take a look at What is dependency injection?.
(*) Unless MyOtherImplementationClass inherits from MyImplementationClass.
First you can not create object of Interface. 2nd point using the interface help you to migrate to new class implementation with minimal changes
As in the places of your coding you will work against the Interface not the the class so if tomorrow you have changed the Concrete class , you just need to modify it in one place and all the code will switch to new class.