📅  最后修改于: 2021-01-09 11:49:26             🧑  作者: Mango
Final是一个关键字,用于防止将超类成员继承到派生类中。您也可以声明最终变量,方法和类。
您不能在子类中覆盖最终变量。让我们来看一个例子。
class Vehicle{
final val speed:Int = 60
}
class Bike extends Vehicle{
override val speed:Int = 100
def show(){
println(speed)
}
}
object MainObject{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
输出:
Error - value speed cannot override final member
父类中的final方法声明不能被覆盖。如果不想覆盖它,则可以采用任何方法进行最终处理。尝试覆盖最终方法将导致编译时错误。
class Vehicle{
final def show(){
println("vehicle is running")
}
}
class Bike extends Vehicle{
//override val speed:Int = 100
override def show(){
println("bike is running")
}
}
object MainObject{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
输出:
method show cannot override final member
override def show(){
^
one error found
您也可以进行最后一堂课。最终课程无法继承。如果您将课程定为最终课程,则无法进一步扩展。
final class Vehicle{
def show(){
println("vehicle is running")
}
}
class Bike extends Vehicle{
override def show(){
println("bike is running")
}
}
object MainObject{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
输出:
error: illegal inheritance from final class Vehicle
class Bike extends Vehicle{
^
one error found