How does one use polymorphism instead of instanceof? (And why?)

后端 未结 7 1659
刺人心
刺人心 2020-12-03 14:23

If we take the code below:

Shape p1 = new Square();
Square c1;
if(p1 instanceof Square) {
  c1 = (Square) p1;
}

What does it mean t

7条回答
  •  时光说笑
    2020-12-03 15:12

    I assume "Shape" is an interface, and "Square" an implementation of that interface.

    Now, if you need to call a method that's declared for the Shape interface (typical example is Shape.getArea()), you shouldn't care whether it's a Square or something else, and call that function.

提交回复
热议问题