w3resource

Scala Program: Employee class with details display method

Scala OOP Exercise-6 with Solution

Write a Scala program that creates a class Employee with properties like name, age, and designation. Implement a method to display employee details.

Sample Solution:

Scala Code:

class Employee(val name: String, val age: Int, val designation: String) {
  def displayDetails(): Unit = {
    println("Employee Details:")
    println(s"Name: $name")
    println(s"Age: $age")
    println(s"Designation: $designation")
  }
}

object EmployeeApp {
  def main(args: Array[String]): Unit = {
    val employee = new Employee("Pero Janae", 30, "Sales Manager")
    employee.displayDetails()
  }
}

Sample Output:

Employee Details:
Name: Pero Janae
Age: 30
Designation: Sales Manager

Explanation:

In the above exercise,

  • The "Employee" class is defined with a constructor that takes name, age, and designation as parameters and initializes the corresponding properties. The properties are defined as val, making them read-only.
  • The "displayDetails()" method is defined within the Employee class. It simply prints out employee details, including name, age, and designation.
  • The "EmployeeApp" object contains the "main()" method where you can test functionality. It creates an instance of "Employee" with sample values and calls the "displayDetails()" method to print employee details.

Scala Code Editor :

Previous: BankAccount class with deposit and withdrawal methods.
Next: Car class with information display method.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.