摘要
这篇博客,主要讲解 Scala 中类的创建,类的构造函数,类的继承,方法重写等基础知识。
类的创建和类的构造函数
class EPerson(name: String, birthYear: Int) {
val pName = name // 没有private修饰符则认为是public
val pBirthYear = birthYear
def introduction():String = {
"name: " + pName + " | birthYear: " + pBirthYear
}
}
说明:(name: String, birthYear: Int) 中的 name 和 birthYear 是类的传入参数,由于没有指定属性,因此是 private [this] val 类型,即本类私有的常量属性。
可以为 EPerson 加入构造函数,采用 this
方法,如下所示:
class EPerson(name: String, birthYear: Int) {
val pName = name // 没有private修饰符则认为是public
val pBirthYear = birthYear
def this(name: String) = {this(name, 1988)} // 只需传入name即可
def this() = {this("John Doe", 1988)} // 无需传入参数
def introduction():String = {
"name: " + pName + " | birthYear: " + pBirthYear
}
}
在 main 函数中,可以通过类似 Java 的 new ClassName 的方式创建类的实例:
val xp1 = new EPerson("xp1", 1963)
val xp2 = new EPerson("xp2")
val xp3 = new EPerson()
然而,Scala 中主流的创建类的方式是通过 apply,也就是通过伴生类
和伴生对象
的方式来创建类,示例如下:
class EPerson(name: String, birthYear: Int) {
val pName = name // 没有private修饰符则认为是public
val pBirthYear = birthYear
def introduction():String = {
"name: " + pName + " | birthYear: " + pBirthYear
}
}
object EPerson {
def apply(name: String, birthYear: Int) = {
new EPerson(name, birthYear)
}
def apply(name: String) = {
new EPerson(name, 1988)
}
def apply() = {
new EPerson("John Doe", 1988)
}
}
创建类的实例的语句,如下所示:
val xp1 = EPerson.apply("xp1", 1963)
val xp2 = EPerson.apply("xp2")
val xp3 = EPerson.apply()
类的继承和方法重写
新建一个 EEmployee 类,来继承 EPerson,并且重写 introduction 方法,代码如下所示:
class EEmployee(name: String, birthYear: Int, salary: Double)
extends EPerson(name, birthYear) {
val eSalary = salary
override def introduction():String = {
super.introduction() + " | salary: " + eSalary
}
}
创建 EEmployee 实例并且 introduction 的结果如下:
val ep1 = new EEmployee("ep1", 1988, 2.3)
println(ep1.introduction())
输出: name: ep1 | birthYear: 1988 | salary: 2.3
8/25/2016 8:56:46 PM
This work is licensed under a CC A-S 4.0 International License.