ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to override the field of a class

Here, we are going to learn how to override the field of a class in Scala programming language?
Submitted by Nidhi, on June 09, 2021

Problem Solution:

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

Program/Source Code:

The source code to override the field of a class is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to override the field of a class

class A {
  val num: Int = 10;
}

class B extends A {
  override val num: Int = 20;
}

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

    printf("Value of num: %d\n", obj.num);
  }
}

Output:

Value of num: 20

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 data member num initialized with 10. Then we inherited the class B, here we override the data member num using the override keyword and initialized with 20.

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 then set and print the value of overridden data member.

Scala Inheritance Programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.