斯卡拉 |最终的
在 Scala 中, Final是一个关键字,用于通过各种方式对超类或父类施加限制。我们可以将 final 关键字与变量、方法和类一起使用。
以下是在 Scala 中使用 final 关键字的方法
- 斯卡拉最终变量:
Scale final 变量在声明时仅初始化一次,并在整个程序中用作常量。在下面的示例中,变量area是 final ,它被声明为 final 并且在超类shape中声明时也被初始化。如果我们想从派生类 Rectangle 中访问或修改变量区域,那么这是不可能的,因为对变量区域的限制是通过关键字 final 添加的。
Scala final 变量通过以下方式初始化:
- 在声明的同时
- 在静态块中
- 在构造函数中
Scala
// Scala program of using final variable
class Shapes
{
// define final variable
final val area:Int = 60
}
class Rectangle extends Shapes
{
override val area:Int = 100
def display()
{
println(area)
}
}
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
var b = new Rectangle()
b.display()
}
}
Scala
// Scala program of using final method
class Shapes
{
val height:Int = 0
val width :Int =0
// Define final method
final def CalArea(){
}
}
class Rectangle extends Shapes
{
override def CalArea()
{
val area:Int = height * width
println(area)
}
}
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
var b = new Rectangle()
b.CalArea()
}
}
Scala
// Scala program of using final class
final class Shapes
{
// Final variables and functions
val height:Int = 0
val width :Int =0
final def CalArea()
{
}
}
class Rectangle extends Shapes
{
// Cannot inherit Shapes class
override def CalArea()
{
val area:Int = height * width
println(area)
}
}
// Creating Object
object GFG
{
// Main method
def main(args:Array[String])
{
var b = new Rectangle()
b.CalArea()
}
}
运行上述代码时出现以下错误
输出 :
prog.scala:5: error: overriding value area in class Shapes of type Int;
value area cannot override final member
override val area:Int = 100
^
one error found
父类(Shapes)中的 final 方法CalArea表明,该方法不能在子类(Rectangle)中覆盖。
斯卡拉
// Scala program of using final method
class Shapes
{
val height:Int = 0
val width :Int =0
// Define final method
final def CalArea(){
}
}
class Rectangle extends Shapes
{
override def CalArea()
{
val area:Int = height * width
println(area)
}
}
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
var b = new Rectangle()
b.CalArea()
}
}
运行上述代码时出现以下错误
输出 :
prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit;
method CalArea cannot override final member
override def CalArea(){
^
one error found
如果 Scala 中的类是 final 的,那么它不能继承到派生类。继承限制将由 final 关键字添加。在这里,如果类 Shapes 是最终的,那么它的所有成员也是最终的并且不能在派生类中使用。
斯卡拉
// Scala program of using final class
final class Shapes
{
// Final variables and functions
val height:Int = 0
val width :Int =0
final def CalArea()
{
}
}
class Rectangle extends Shapes
{
// Cannot inherit Shapes class
override def CalArea()
{
val area:Int = height * width
println(area)
}
}
// Creating Object
object GFG
{
// Main method
def main(args:Array[String])
{
var b = new Rectangle()
b.CalArea()
}
}
运行上述代码时出现以下错误
输出 :
prog.scala:4: error: illegal inheritance from final class Shapes
class Rectangle extends Shapes{
^
one error found