Exactly What would this m开发者_开发技巧ean:
Car is an interface
Audi is a class
Car x = new Audi();
I'm not sure about having an interface as a type for a class. Thanks
You don't have an interface as type of a class. The real (runtime) type of the x
variable is Audi
which is not an interface. At runtime you can never instantiate an interface, only actual types. But because you have typed the x
variable as Car
at compile time only this interface will be known and you will be able to call only methods on this interface:
Car x = new Audi();
x.AMethodOnTheInterface();
Your code will work perfectly fine; this is a very common idiom.
You can declare a variable or field as an interface, then put instances of any class that implements the interface into it.
For example, people frequently write
List<Car> myCars = new ArrayList<Car>();
It's common advice to program to the interface, rather than to the implementation. That's what you're doing here. What it means is that x
is an object that implements Car
; that is, that it can do all the things that a Car can do, and that's all you care about (and can use, unless you do some casting). It works because an Audi is always a Car, so you can use it and assign it just about anywhere you need a Car.
This is a common, and often beneficial, thing; absent casting, it keeps you from having to care that your Car is really an Audi (and writing a bunch of Audi-specific code that'd be potentially useless if your Car ever has to be something besides an Audi).
The difference is between the "declared type" and the "implementing type." The former of which can be any abstraction above the latter.
In this particular case, the code is declaring a Car
which is being satisfied (implemented) by an instance of Audi
. Any implementation of Car
will do in this case.
A more obvious example of something like this would be to have a public member of a class be of type Car
. In such a case, the internal implementation of that class needs a Car
, any Car
, in order to accomplish some task. You can set it to any object which implements Car
.
What you're doing there is coding to an interface rather than an implementation, which, where you can, is a good thing to do since it allows you to swap over the implementation should you need to with minimal difficulty. It's the same principle as doing:
List<String> strs = new ArrayList<String>();
You're creating an arraylist there which is the implementation type, but the reference is of type list. You then do all operations on the object that conforms to the list interface - if you need to this gives you the flexibility to swap the implementation to a linked list or even another list you've coded yourself, without breaking any other code (as long as it's been implemented correctly of course!)
The same principle applies here with your car object.
精彩评论