104
Scala Final
Final is a keyword, which is used to prevent inheritance of super class members into derived class. You can declare final variables, methods and classes also.
Scala Final Variable Example
You can’t override final variables in subclass. Let’s see an example.
Output:
Error - value speed cannot override final member
Scala Final Method
Final method declare in the parent class can’t be override. You can make any method to final if you don’t want to get it overridden. Attempt to override final method will cause to a compile time error.
Scala Final Method Example
Output:
method show cannot override final member override def show(){ ^ one error found
Scala Final Class Example
You can also make final class. Final class can’t be inherited. If you make a class final, it can’t be extended further.
Output:
error: illegal inheritance from final class Vehicle class Bike extends Vehicle{ ^ one error found
Next TopicScala Abstract Class