In Scala, Final is a keyword and used to impose restriction on super class or parent class through various ways. We can use final keyword along with variables, methods and classes.
Following are the ways of using final keyword in Scala
Scale final variable initialized only once while declared and used as constant throughout the program. In below example, variable area is final which is declared as final and also initialized while declare in superclass shapes. if we want to access or modify the variable area from derived class Rectangle then it is not possible because the restriction on variable area is added by keyword final.
Scala final variable initialized by following ways:
- While declaring
- In static block
- In Constructor
// 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()
}
}
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
// 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 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