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 o开发者_如何学Pythonf 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:
IBlah
^
|
AbstractBlah
^
|
BlahImpl
If IBlah
is an interface and AbstractBlah
is an abstract class and BlahImpl
is a concrete class, the following lines of code are all invalid:
IBlah blah1 = new IBlah();
IBlah blah2 = new AbstractBlah();
AbstractBlah blah3 = new AbstractBlah();
The following lines of code are both valid:
IBlah blah1 = new BlahImpl();
AbstractBlah blah3 = new BlahImpl();
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:
interface IBlah {
void doBlah();
}
That interface could be implemented and instantiated in one fell swoop like so:
IBlah blah = new IBlah() {
public void doBlah() {
System.out.println("Doing Blah");
}
};
"A BlahImpl
object is instantiated, and assigned to variable blah
as an implementation of interface IBlah
." We could also call it a cast, since there is an implicit cast by assigning it like that.
Edit: your first answer sounds reasonable too, the second one does not.
Maybe this is clearer:
Create new instance of BlahImpl
and up cast it to IBlah
and assign it to blah
.
精彩评论