How to use polymorphism to make list with different types in java?

后端 未结 5 1304
北荒
北荒 2020-12-22 04:30

I have 3 Classes Circle, Rectangle and Square

I want to get required data for each of above classes and create them by user .

It me

5条回答
  •  太阳男子
    2020-12-22 05:00

    If you want an official reference on how polymorphism works in java, there's the Oracle Java Tutorial's section on Polymorphism, which explains that a variable of a given class can hold values of any of its subclasses, and that methods called on a superclass variable will use implementations in the subclass if they exist.

    To tailor the information in this tutorial to your question:
    A List can be considered a collection of variables, and a list of Shapes as described in previous answers can contain of instances of any subclass of Shape, i.e. Square, Rectangle, or Circle. Calling the calculateArea and calculatePrimeter methods on elements of the list will call the corresponding method for that shape.

提交回复
热议问题