![]() |
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. Real-life Illustration: Polymorphism A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations. This is called polymorphism. Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms. Types of polymorphismPolymorphism is mainly divided into two types:
ExamplesExample 1: Compile-time Polymorphism Let’s start with compile-time polymorphism. In compile-time polymorphism, the name functions, that is, the signature remains the same but parameters or return type is different. At compile time, the compiler then resolves which functions we are trying to call based on the type of parameters and more. Check out this example: Kotlin
Output: 8 8.6 8.646 Example 2: Runtime Polymorphism Now, let’s talk about run-time polymorphism. In run-time polymorphism, the compiler resolves a call to overridden/overloaded methods at runtime. We can achieve run-time polymorphism using method overriding. Let’s try an example where we extend a superclass and override one of its member methods: Kotlin
Output: printing method 1 from inside Sup printing method 2 from inside Sup printing method 1 from inside Sum printing method 2 from inside Sup Here, the compiler resolves, at run-time, which method to execute. |
Reffered: https://www.geeksforgeeks.org
Kotlin |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 8 |