Scala program to implement method overriding

Here, we are going to learn how to implement method overriding in Scala programming language?
Submitted by Nidhi, on June 09, 2021 [Last updated : March 11, 2023]

Scala – Implementing Method Overriding

Here, we will override a method using the override keyword. We can implement the method with the same name using method overriding.

Scala code to implement method overriding

The source code to implement method overriding is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to implement method overriding

class A {
  def MyMethod() {
    println("Message from class A");
  }
}

class B extends A {
  override def MyMethod() {
    println("Message from class B");
  }
}

object Sample {
  def main(args: Array[String]) {
    var obj = new B();

    obj.MyMethod();
  }
}

Output

Message from class B

Explanation

In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample.

Here, we created two classes "A" and "B". The class "A" contains a method Method1(). Then we override the Method1() into derived class "B" using the override keyword.

Then we defined the main() function in the Sample object. The main() function is the entry point for the program.

In the main() function, we created the object of class "B" and called the overridden method, and print the "Message from class B" message on the console screen.

Scala Inheritance Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.