Scala program to implement simple inheritance

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

Scala - Simple Inheritance Example

Here, we will create two classes to implement simple inheritance. And, we will inherit the features of the base class into the derived class using the extends keyword.

Scala code to implement simple inheritance

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

// Scala program to implement simple inheritance

class Employee {
  var empId: Int = 0;
  var empName: String = "";

  def setEmp(id: Int, name: String) {
    empId = id;
    empName = name;
  }
  def printEmp() {
    printf("\tEmployee Id  : %d\n", empId);
    printf("\tEmployee Name: %s\n", empName);
  }
}

class Accountant extends Employee {
  var salary: Float = 0
  var bonus: Float = 0

  def setInfo(id: Int, name: String, s: Float, b: Float) {
    setEmp(id, name);
    salary = s;
    bonus = b;
  }
  def printInfo() {
    printEmp();
    printf("\tEmployee Salary: %f\n", salary);
    printf("\tEmployee Bonus : %f\n", bonus);
  }
}

object Sample {
  def main(args: Array[String]) {
    var acc1 = new Accountant();
    var acc2 = new Accountant();

    acc1.setInfo(101, "Arun", 12345.23f, 220.34f);
    acc2.setInfo(102, "Anup", 12345.23f, 220.34f);

    println("Accountant1:");
    acc1.printInfo();

    println("Accountant2:");
    acc2.printInfo();
  }
}

Output

Accountant1:
	Employee Id  : 101
	Employee Name: Arun
	Employee Salary: 12345.230469
	Employee Bonus : 220.339996
Accountant2:
	Employee Id  : 102
	Employee Name: Anup
	Employee Salary: 12345.230469
	Employee Bonus : 220.339996

Explanation

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

And, we created two classes Employee and Accountant. The Employee class contains setEmp() and printEmp() function and Accountant class contains setInfo() and printInfo().

And, we inherited the Employee class inherited into the Accountant class using the extend 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 two objects of the Accountant class and called methods to set and print information regarding Accountant.

Scala Inheritance Programs »






Comments and Discussions!

Load comments ↻






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