What is polymorphism, what is it for, and how is it used?

前端 未结 28 2761
南笙
南笙 2020-11-21 07:08

What is polymorphism, what is it for, and how is it used?

28条回答
  •  心在旅途
    2020-11-21 07:44

    Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.

    for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well. so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.

提交回复
热议问题