VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-field-overriding/

⇱ Scala | Field Overriding - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala | Field Overriding

Last Updated : 17 Jan, 2022

In any object-oriented programming language, Overriding is a feature that allows a subclass to provide a specific implementation of a method or field that is already provided by one of its super-classes. In Scala, Overriding is further explicitly stated in comparison to Overriding in Java, as here both methods as well as Fields can be overridden but it has a few restrictions which are obligatory to follow. 
 

Rules for the Field Overriding


The rules for the field overriding are as follows: 
 

  • The one of the foremost rule is that we must utilize the keyword override or override notation while overriding the fields of the super-class in the sub-classes otherwise the compiler will throw an error and will terminate the execution of the program. 
     
  • In order to execute a Field Overriding, we need to override variables that are declared utilizing only the val keyword in both super class as well as sub-classes. 
     
  • Field overriding cannot override var, because we can both read as well as write var
     


Now, lets see some examples to illustrate these restrictions.
Example : 
 


Output: 
It is a circle.
It is a square.

 

Now, we can see in above example that val is utilized in both super class and subclass so, overriding of the field was practicable otherwise it would have thrown an error. Here, the field in the super class is val which is overridden in the sub-classes using the override keyword.
Example : 
 


Output: prog.scala:17: error: overriding value description in class Shapes of type String; 
variable description needs to be a stable, immutable value 
override var description:String ="It is a circle." 

prog.scala:32: error: overriding value description in class Shapes of type String; 
variable description needs to be a stable, immutable value 
override var description:String ="It is a square." 

two errors found  

It is the same example as above but here errors are found as here, var is used in the sub-classes to override the fields which is not possible as val cannot be overridden by the var as stated above.
Example : 
 


Output: prog.scala:17: error: overriding variable number in class Animals of type Int; 
variable number cannot override a mutable variable 
override var number:Int = 4 

one error found  

Here, var is utilized for overriding fields which is not possible as stated in the above rules so, an error is found.
 

Comment
Article Tags:

Explore