Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as means many and means types. Scala implements polymorphism through virtual functions, overloaded functions and overloaded operators. Polymorphism is one of the most important concept of object oriented programming language. The most common use of polymorphism in object oriented programming occurs when a parent class reference is used to refer to a child class object. Here we will see how represent any function in many types and many forms. Real life example of polymorphism, a person at the same time can have different roles to play in life. Like a woman at the same time is a mother, a wife, an employee and a daughter. So the same person has to have many features but has to implement each as per the situation and the condition. Polymorphism is considered as one of the important features of Object Oriented Programming. In Scala the function can be applied to arguments of many types, or the type can have instances of many types.
There are two principal forms of polymorphism:
- Subtyping: In subtyping a subclass’s instance can be passed to a base class
- Generics: By type parameterization, instances of a function or class are created .
Below are some examples:
First Execution:120 Second Execution:120 Third Execution:300
In above example we have three functions whose name is same (func) but parameters are different.
The Vehicle is:swift The Vehicle category is:hatchback The Vehicle is:honda-city The Vehicle category is:sedan Student Name is:Ashok Marks obtained are:95 Sum is:30
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.