Method Overriding in Scala
Last Updated :
25 Apr, 2019
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 :
Scala
// 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())
}
}
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 :
Scala
// 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))
}
}
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:
- Auxiliary Constructors are defined like methods utilizing def and this keywords, where this is the name of the constructor.
- Primary Constructors begins from the beginning of the class definition and stretches the whole body of the class.
Lets see some examples now.
Example :
Scala
// 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()
}
}
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 :
Scala
// 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)
}
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.
Similar Reads
Collections
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents
5 min read
A list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built u
6 min read
A set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen
6 min read
Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: m
5 min read
Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr
6 min read
Array in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size canât change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala.collection.mutable.ArrayBuf
4 min read
Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
5 min read
A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite
3 min read
Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i
7 min read
A set is a collection which only contains unique items which are not repeatable. A BitSet is a collection of small integers as the bits of a larger integer. Non negative integers sets which represented as array of variable-size of bits packed into 64-bit words is called BitSets. The largest number s
5 min read
HashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic
4 min read
A stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, v
3 min read
HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map. Syntax: var hashMapName = HashMap("key1"->"value1", "key2"->"value
3 min read
Set is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions: scala.collection.immutable.TreeSet and scala.collection.mutable.TreeSet. Syntax
4 min read
An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther
5 min read
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The insta
3 min read