Using interfaces in java
Suppose there in an interface Displaceable and a class Circle which implements Displaceable. Displaceable has a method named move() which of co开发者_开发问答urse is implemented in Circle.
What would happen in the following scenario?
Circle a = new Circle(..);
Displaceable b = a;
b.move()
Would the object refer to the Circle's move method?
Yes, b.move() would be the same as calling a.move() in your scenario. This is polymorphism in action.
Yes.
Displaceable b
says what can be done to b. The compiler can (and does) check whether that method is available on that type (Displaceable) at compile time.
How this is done is not necessarily clear at compile time. It's up to the implementation, at run-time, to just do it (move).
At compile time, the promise (I can move!) is checked. At runtime, the code has to prove that it really can :)
Even if Displaceable
were a class and not an interface, and implemented move
itself, the actual move
called run-time would still be the implementation (if that implementation, Circle
, would have overridden the Displaceable
implementation).
The only time there is a compile-time binding of a call (to e.g. move
) to the actual implementation is when a method is defined as being static. That's also why static methods can't be defined in interfaces, as they don't hold implementation.
Yes. Cool, isn't it? That's the beauty of polymorphism.
For the sake of completeness, I should add that if Circle
extends some other class that has a move()
method, it's possible that the method that gets called isn't defined in Circle
, but some superclass.
In general, though, you've got the right idea.
Yes, absolutely.
Its the same thing as doing this
void move(Displaceable b){
b.move();
}
//somewhere else
move (new Circle(args));
move (new Square(args));
move (new Triangle(args));
If you think about it, its equivalent to have an abstract superclass Figure
public abstract class Figure{
public abstract move();
}
//Circle extends Figure;
Figure f = new Circle(args);
f.move();
精彩评论