![]() |
VOOZH | about |
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:
Below are some examples: Example #1:
Output:
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. Example #2:
Output:
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
In Scala, polymorphism refers to the ability of a function, method or class to take on multiple forms or behaviors based on the types of input arguments or data it receives. There are two types of polymorphism in Scala:
Area of circle: 12.566370614359172 Area of rectangle: 12.0
In this code, we have defined three classes Shape, Circle, and Rectangle. Shape is the base class which has a method area() that returns the area of the shape. Circle and Rectangle are the derived classes which inherit from the Shape class and override the area() method to calculate the area of a circle and a rectangle respectively.
In the Main object, we create an instance of Circle and Rectangle classes and call their area() method. Since the area() method is overridden in the derived classes, the correct implementation is used for each object, and the output shows the calculated areas of the circle and rectangle.