ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to demonstrate the final data member

Here, we are going to demonstrate the final data member in Scala programming language.
Submitted by Nidhi, on July 07, 2021

Problem Solution:

Here, we will demonstrate the use of the final data member. If we created a final data member in a class then it cannot be overridden in the derived class. To create a final data member, we need to use the final keyword.

Program/Source Code:

The source code to demonstrate the final data member is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate the 
// final data member

class Demo1 {
  final val num1: Int = 10;
  val num2: Int = 10;
}

class Demo2 extends Demo1 {
  // Cannot override final data member of class
  // val num1:Int=20;
  override val num2: Int = 20;
}

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

    printf("Num1 : %d\n", obj.num1);
    printf("Num2 : %d\n", obj.num2);
  }
}

Output:

Num1 : 10
Num2 : 20

Explanation:

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

Here, we created two classes Demo1 and Demo2. The Demo1 class contains two data members num1 and num2. The num1 is the final type. Then it cannot be overridden in any derived class. Then we override the num2 in the Demo2 class.

In the main() function, we created the object of the Demo2 class and print the values of data members on the console screen.

Scala Final Variables, Methods & Classes Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

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.