Trying to get clarifications on when you create a new variable, based on an interface or abstract class, and new it when a specific implementation.
Example:
IBlah blah = new BlahImpl();
How would you read that out?
Is it:
A reference variable blah of type IBlah is instantiated with the class BlahImpl?
And so the reference variable will be bound to IBlah, and hence only have the methods/instance and static variables of IBlah but use BlahImpl classes implementaiton of those properties/vars?
Just trying to get my terminology corrected.
Interfaces and abstract classes can never be instantiated. What you can do as you have in your example is to instantiate a concrete class but assign the resulting object to an interface.
Consider the following class hierarchy:
If
IBlahis an interface andAbstractBlahis an abstract class andBlahImplis a concrete class, the following lines of code are all invalid:The following lines of code are both valid:
So you can only instantiate concrete a class but the variable you assign that to can be any super-type (a parent class or interface implemented by the class) of the concrete class.
You can refer to and use the concrete class through the interface or abstract class variable. In fact this is actually encouraged as programming to an abstract class (or interface) makes your code more flexible.
It is possible to create a concrete class from an interface or abstract class in in-place. So if we have an interface like this:
That interface could be implemented and instantiated in one fell swoop like so: