Polymorphism in Scala Programming Language

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

Polymorphism is the ability of any data to be processed in more than one form.  Scala implements polymorphism through virtual functions, overloaded functions and overloaded operators. Polymorphism is one of the most important concept of object oriented programming language.

                                  Two principal forms of Polymorphism:

  • Subtyping  – A Instance can be passed to base class.
  • Generics  – Instance of a function or classes are created.

Run the following commands to see the usage of  many functions at same time:

OUTPUT:

Polymorphism:

1.     Method over-riding

2.     Method over-loading

1. Program to calculate Area of shapes usingmethod overriding.

package Polymorphism

class Shape {

def Area(l:Double, b:Double, r:Double)=
    {
0.0
}
  }

class Rectangle extends Shape
  {

override defArea(l:Double, b:Double, r:Double)=
    {
      (l * b)
    }
  }

class Circle extends Shape
  {

override defArea(l:Double, b:Double, r:Double)=
    {
      ((3.14)* r * r)
    }
  }

object s
  {

defmain(args:Array[String])
    {

var rectangle = new Rectangle()
var circle = new Circle()

println(“Area of Rectangle is : ” + rectangle.Area(3, 11, 4))

println(“Area of Circle is : ” + circle.Area(1, 7, 10))
    }

Quick Support

image image