Open In App

Call a method on a Super Class in Scala

Last Updated : 05 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

This concept is used when we want to call super class method. So whenever a base and subclass have same named methods then to resolve ambiguity we use super keyword to call base class method. The keyword “super” came into this with the concept of Inheritance.

Below is the example of call a method on a superclass.

Example #1:




// Scala program to call a method
// on a superclass in Scala
  
/* Base class ComputerScience */
class ComputerScience
{
    def read 
    {
        println("I'm reading")
    }
    def write
    {
        println("I'm writing")
    }
}
  
/* Subclass Scala */
class Scala extends ComputerScience
{
    // Note that readThanWrite() is only in Scala class 
    def readThanWrite() 
    {
        // Will invoke or call parent class read() method 
        super.read
          
        // Will invoke or call parent class write() method 
        super.write
    }
}
  
// Creating object 
object Geeks
{
    // Main method 
    def main(args: Array[String]) 
    
        var ob = new Scala();
          
        // Calling readThanWrite() of Scala
        ob.readThanWrite();
    


Output:

I'm reading
I'm writing

In above example, we are calling multiple method of super class by using super keyword.

Example #2:




// Scala program to call a method
// on a superclass in Scala
  
/* Super class Person */
class Person 
    def message() 
    
        println("This is person class"); 
    
  
  
/* Subclass Student */
class Student extends Person 
  
   override def message()
    
        println("This is student class")
    }
      
    // Note that display() is only in Student class 
    def display() 
    
        // will invoke or call current class message() method  
        message ()
          
        // will invoke or call parent class message() method 
        super.message
    
  
/* Creating object */
object Geeks
    // Main method
    def main(args: Array[String]) 
    
        var s = new Student(); 
  
        // Calling display() of Student 
        s.display(); 
    


Output:

This is student class
This is person class

In the above example, we have seen that if we only call method message() then, the current class message() is invoked but with the use of super keyword, message() of super class could also be invoked.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads