Scala 多态性
多态性 是指任何数据都能以一种以上的形式被处理。这个词本身就表明了这个意思,因为
,意思是很多,
,意思是类型。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 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);
}
}
输出
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
极客教程