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

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

    Polymorphism lets you change the behaviour of something depending on which type is it. Not sure how to explain it with your example since you could just assign it to a Square straight away if it is important that it is a Square for some reason. Sometimes you need to subclass as it might have additional behaviour etc, but consider this example:

    class Shape
    {
        abstract void draw();
    }
    
    class Square extends Shape
    {
        void draw()
        {
            // square drawing goes here
        }
    }
    

    The draw method here is an example of polymorphism as we have a base class Shape that says that all shapes now how to draw themselves, but only the Square knows how to draw a Square.

    0 讨论(0)
提交回复
热议问题