oop-examples/lessons/Polymorphism.md

860 B

Polymorphism

Polymorphism is the ability to treat subclasses like their base classes, for example passing cat, which extends animal to a function that expects an animal as parameter. or storing objects of different types that all extend a common class in an array of that common type.

You lose acess to the properties of the subclass, but you can still access the base class like usual. When the subclass overrides behaviour of the base class, the overridden functionality in the subclass is still called.

You can regain access to properties of the subclass with casting, but you have to make sure that the object is actually an instance of that class or you might run into runtime errors.