Using interfaces in java..Newb question

Suppose the Displaceable interface and the Circle class that implements Displacementable. The relocatable has a method called move (), which, of course, is implemented in Circle.

What will happen in the following scenario?

Circle a =  new Circle(..);
Displaceable b = a;
b.move()

Will the object refer to the circular movement method?

+3
source share
4 answers

Yes, b.move () will be the same as calling a.move () in your script. This is polymorphism in action.

+11
source

Yes.

Displaceable bsays what can be done with b. The compiler can (and does) check whether this method is available for this type (offset) at compile time.

, . , , ().

( !). , :)

Displaceable , , move, move ( , Circle, Displaceable).

, (, move) - . , .

+4

, .

,

void move(Displaceable b){
    b.move();
}

//somewhere else
move (new Circle(args));

move (new Square(args));

move (new Triangle(args));

, .

public abstract class Figure{
     public abstract move();
}
//Circle extends Figure;

Figure f = new Circle(args);

f.move();
+2

. , ? .

For completeness, I must add that if you Circleextend some other class that has a method move(), it is possible that the method that is being called is not defined in Circle, but some superclass.

In general, however, you have the right idea.

+2
source

Source: https://habr.com/ru/post/1744034/


All Articles