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

后端 未结 7 1614
刺人心
刺人心 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:18

    That's not really a strong example, but here's what your code would look like.

    Square c1 = new Square();
    Shape p1 = c1;
    

    (given that Square extends Shape of course)

    Much better isn't it?

    As for "why is it better", the other answers give out some important points.

提交回复
热议问题