Scala多态性介绍和用法指南

2021年3月9日16:20:06 发表评论 887 次浏览

多态

是指以多种形式处理任何数据的能力。这个词本身的意思是

聚

意味着很多

态射

表示类型。 Scala通过虚函数, 重载函数和重载运算符实现多态。多态是面向对象编程语言最重要的概念之一。当使用父类引用来引用子类对象时, 多态性在面向对象的编程中最常见的用法发生了。在这里, 我们将看到如何以多种类型和多种形式表示任何功能。现实生活中多态的例子, 一个人在同一时间可以扮演不同的角色。就像一个女人在同一时间是母亲, 妻子, 雇员和女儿。因此, 同一个人必须具有许多功能, 但必须根据情况和条件实施每个功能。多态被认为是面向对象编程的重要特征之一。在Scala中, 该函数可以应用于多种类型的参数, 或者该类型可以具有多种类型的实例。

多态性有两种主要形式:

  • 子类型化:在子类型化中, 子类的实例可以传递给基类
  • 泛型:通过类型参数化, 可以创建函数或类的实例。

以下是一些示例:

范例1:

// 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 );
     } 
}

输出如下:

First Execution:120
Second Execution:120
Third Execution:300

在上面的示例中, 我们有三个函数, 它们的名称相同(func), 但参数不同。

范例2:

// Scala program to illustrate polymorphism
// concept
class example 2
{ 
     // 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 example 2 (); 
         A.func( "swift" , "hatchback" ); 
         A.func( "honda-city" , "sedan" ); 
         A.func( "Ashok" , 95 );
         A.func( 10 , 20 );
     } 
}

输出如下:

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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: