Call a method on a Super Class in Scala
Last Updated :
05 Aug, 2019
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:
class ComputerScience
{
def read
{
println( "I'm reading" )
}
def write
{
println( "I'm writing" )
}
}
class Scala extends ComputerScience
{
def readThanWrite()
{
super .read
super .write
}
}
object Geeks
{
def main(args : Array[String])
{
var ob = new 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:
class Person
{
def message()
{
println( "This is person class" );
}
}
class Student extends Person
{
override def message()
{
println( "This is student class" )
}
def display()
{
message ()
super .message
}
}
object Geeks
{
def main(args : Array[String])
{
var s = new 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
Share your thoughts in the comments
Please Login to comment...