Open In App

Scala | Polymorphism

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly  means many and morphism  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: Example #1: 

Scala

// Scala program to shows the usage of
// many functions with the same name
class example
{
     
    // This is the first function with the name fun
    def func(a:Int)
    {
        println("First Execution:" + a);
    }
     
    // This is the second function with the name fun
    def func(a:Int, b:Int)
    {
        var sum = a + b;
        println("Second Execution:" + sum);
    }
     
    // This is the first function with the name fun
    def func(a:Int, b:Int, c:Int)
    {
        var product = a * b * c;
        println("Third Execution:" + product);
    }
}
 
// Creating object
object Main     
{
    // Main method
    def main(args: Array[String])
    {
        // Creating object of example class
        var ob = new example();
        ob.func(120);
        ob.func(50, 70);
        ob.func(10, 5, 6);
    }
}

                    

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: 

Scala

// Scala program to illustrate polymorphism
// concept
class example2
{
    // Function 1
    def func(vehicle:String, category:String)    
    {
        println("The Vehicle is:" + vehicle);
        println("The Vehicle category is:" + category);
    }
     
    // Function 2
    def func(name:String, Marks:Int)     
    {
        println("Student Name is:" + name);
        println("Marks obtained are:" + Marks);
    }
     
    // Function 3
    def func(a:Int, b:Int)
    {
        var Sum = a + b;
        println("Sum is:" + Sum)
    }
     
}
 
// Creating object
object Main
{
    // Main method
    def main(args: Array[String])
    {
        var A = new example2();
        A.func("swift", "hatchback");
        A.func("honda-city", "sedan");
        A.func("Ashok", 95);
        A.func(10, 20);
    }
}

                    

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:

Sure! Here’s an example of runtime polymorphism or method overriding in Scala:

Scala

class Shape {
  def area(): Double = 0.0
}
 
class Circle(radius: Double) extends Shape {
  override def area(): Double = math.Pi * radius * radius
}
 
class Rectangle(length: Double, width: Double) extends Shape {
  override def area(): Double = length * width
}
 
object Main {
  def main(args: Array[String]) {
    val circle = new Circle(2.0)
    val rectangle = new Rectangle(3.0, 4.0)
    println(s"Area of circle: ${circle.area()}")
    println(s"Area of rectangle: ${rectangle.area()}")
  }
}

                    

Output
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.

Sure! Here are some advantages and disadvantages of polymorphism in Scala:

Advantages:

  1. Code reusability: Polymorphism allows for code reusability, as methods can be defined in a base class and then overridden in derived classes, reducing code duplication.
  2. Flexibility: Polymorphism provides flexibility, as it allows you to write more generic code that can be applied to a wider range of objects, instead of writing separate code for each object.
  3. Extensibility: Polymorphism makes it easier to extend your code, as you can simply create new classes that inherit from existing classes and override or add methods as necessary.

Disadvantages:

  1. Runtime performance overhead: Polymorphism can introduce some runtime performance overhead, as the method to be called is determined at runtime, which requires additional time to resolve the method call.
  2. Complexity: Polymorphism can make code more complex and harder to understand, especially when multiple levels of inheritance are involved.
  3. Name clashes: Polymorphism can lead to name clashes, as multiple classes can define methods with the same name and parameters. This can lead to confusion and errors if the wrong method is called.
  4. Overall, the advantages of polymorphism generally outweigh the disadvantages, as it provides greater code reusability, flexibility, and extensibility, which are important principles of good software design.


Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads