Method Overriding in Scala

Method Overriding in Scala is identical to the method overriding in Java but in Scala, the overriding features are further elaborated as here, both methods as well as var or val can be overridden. If a subclass has the method name identical to the method name defined in the parent class then it is known to be Method Overriding i.e, the sub-classes which are inherited by the declared super class, overrides the method defined in the super class utilizing the override keyword.

Flow chart of method overriding

Lets, see the flow chart of the method overriding in order to visualize it explicitly.

Here, in the diagram stated above School is the super-class which has a method defined in it which is named as NumberOfStudents() and this method is overridden by the sub-classes i.e, class 1, class 2, class 3. so, all the sub-classes has the same named method as defined in the super-class.

When to apply Method Overriding ?

when a subclass wishes to impart a particular implementation for the method defined in the parent class then that subclass overrides the defined method from the parent class. When we wish to reconstruct the method defined in the super class then we can apply method overriding.
Let’s see an example which is related to the diagram mentioned above of the method overriding.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of method overriding
  
// Creating a super class
class School
  
    // Method defined
    def NumberOfStudents()=
    
        0 // Utilized for returning an Integer
    
  
// Creating a subclass 
class class_1 extends School
{
      
    // Using Override keyword
    override def NumberOfStudents()=
    
        30
    
  
// Creating a subclass 
class class_2 extends School
  
    // Using override keyword 
    override def NumberOfStudents()=
    
        32
    
  
// Creating a subclass
class class_3 extends School
      
    // Using override keyword
    override def NumberOfStudents()=
    
        29
    
  
// Creating object 
object GfG
  
    // Main method
    def main(args:Array[String])
    
          
        // Creating instances of all
        // the sub-classes
        var x=new class_1() 
        var y=new class_2() 
        var z=new class_3()
          
        // Displays number of students in class_1
        println("Number of students in class 1 : "
                                x.NumberOfStudents()) 
          
        // Displays number of students in class_2
        println("Number of students in class 2 : "
                                y.NumberOfStudents())
          
        // Displays number of students in class_3
        println("Number of students in class 3 : " +
                                z.NumberOfStudents()) 
          
    

chevron_right


Output:

Number of students in class 1 : 30
Number of students in class 2 : 32
Number of students in class 3 : 29

In the above example, we have a class named School which defines a method NumberOfStudents() and we have three classes i.e, class_1, class_2 and class_3 which inherit from the super-class School and these sub-classes overrides the method defined in the super-class.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of method overriding
  
// Creating a super class
class Shapes
  
    // Method defined with parameters
    def Area(l:Double, b:Double, r:Double)=
    
      
        0.0 // Utilized for returning double
    
  
// Creating a subclass 
class Rectangle extends Shapes
{
      
    // Overriding method to find
    // area of the rectangle 
    override def Area(l:Double, b:Double, r:Double)=
    
      
        (l * b)
    
  
// Creating a subclass 
class Circle extends Shapes
  
    // Overriding method to find
    // area of the circle
    override def Area(l:Double, b:Double, r:Double)=
    
          
        ((3.14)* r * r)
    
  
// Creating object 
object GfG
  
    // Main method
    def main(args:Array[String])
    
          
        // Creating instances of all
        // the sub-classes
        var rectangle = new Rectangle() 
        var circle = new Circle() 
          
        // Displays area of the rectangle
        println(rectangle.Area(3, 11, 4)) 
          
        // Displays area of the circle
        println(circle.Area(1, 7, 10)) 
          
    

chevron_right


Output:

33.0
314.0

In the above example, Area is a method of the super-class which is to be overridden by the methods defined in the sub-classes. Here, we are finding the area but for different shapes using the same method name i.e, Area thus, we can say that this method overriding can be applied for same kind of operations but for different categories and it is worth noting that the methods must have same data types and same number of parameters as defined in the super class otherwise the compiler will throw an error. Though the order of the parameters in the method defined can be altered in the sub-classes when the method is overridden.

Rules for Method Overriding

There are a few restrictions that we need to follow for method overriding, these are as follows:

  • For method overriding, one of the crucial rule is that the class which is overriding needs to utilize the modifier override or override annotation.
  • Auxiliary constructors are not able to call the super-class constructors immediately. They can hardly call the primary constructors which in reversal will call the super-class constructor.
  • In Method Overriding, we won’t be able to override a var with a def or val, otherwise it throws an error.
  • Here, we won’t be able to override a val in the super-class by a var or def in the subclass, and if the var in the super-class is abstract then we can override it in the subclass.
  • If a field is stated var then it can override the def which is defined in the super-class. The var can only override a getter or setter combination in the super-class.

Note:

  1. Auxiliary Constructors are defined like methods utilizing def and this keywords, where this is the name of the constructor.
  2. Primary Constructors begins from the beginning of the class definition and stretches the whole body of the class.

Lets see some examples now.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of method 
// Overriding
  
// Creating a class
class Animal
{
      
    // Defining a method
    def number()
    
        println("We have two animals")
  
    
  
// Extending the class Animal
class Dog extends Animal
{
  
    // using override keyword
    override def number()
    
          
        // Displays output
        println("We have two dogs"
  
    
  
// Creating object 
object GfG
  
    // Main method
    def main(args:Array[String])
    
          
        // Creating object of the subclass
        // Dog
        var x = new Dog() 
              
        // Calling overridden method
        x.number() 
              
    

chevron_right


Output:

We have two dogs

Here, we have overridden the method utilizing the keyword override. In the above example, the super class Animal has a method named number which is overridden in the subclass Dog. So, the overridden method can be called by creating the object of the subclass.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of method 
// overriding
  
// Creating super-class
class Students(var rank:Int, var name:String)
{
      
    // overriding a method 'toString()'
    override def toString():String =
    {
        " The rank of "+name+" is : "+rank
    }
}
  
// Creating a subclass of Students
class newStudents(rank:Int, name:String)
        extends Students(rank, name){
}
  
// Inheriting main method of 
// the trait 'App' 
object GfG extends App
{
      
    // Creating object of the super-class
    val students = new Students(1, "Geeta Sharma")
      
    // Displays output
    println(students)
      
    // Creating object of the subclass
    val newstudents = new newStudents(3, "Priti Singh")
      
    // Displays output
    println(newstudents)
  
}

chevron_right


Output:

The rank of Geeta Sharma is : 1
The rank of Priti Singh is : 3

Here, the constructor of the super-class i.e, Students is called from the primary constructor of the subclass i.e, newStudents so, the super-class constructor is called utilizing the keyword extends.
Note: The AnyRef class has a toString() method defined in it and as we know that every class is subclass of AnyRef class so, the method toString() is overridden using the keyword override.

Overriding vs Overloading
  • In Scala, method overloading supplies us with a property which permits us to define methods of identical name but they have different parameters or data types whereas, method overriding permits us to redefine method body of the super class in the subclass of same name and same parameters or data types in order to alter the performance of the method.
  • In Scala, method overriding uses override modifier in order to override a method defined in the super class whereas, method overloading does not requires any keyword or modifier, we just need to change, the order of the parameters used or the number of the parameters of the method or the data types of the parameters for method overloading.
Why do we need Method Overriding ?

In order to redefine a single method in different ways, we can do method overriding which helps us to do different operations with same method name. Like, in the diagram shown above has a super-class School which has a method named NumberOfStudents() which is overridden by the sub-classes to perform different actions.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.