w3resource

Scala Program: Create a Person class with properties and methods

Scala OOP Exercise-1 with Solution

Write a Scala program that creates a class called Person with properties like name, age and country. Implement methods to get and set properties.

Sample Solution:

Scala Code:

class Person(var name: String, var age: Int, var country: String) {
  def getName: String = name

  def setName(newName: String): Unit = {
    name = newName
  }

  def getAge: Int = age

  def setAge(newAge: Int): Unit = {
    age = newAge
  }

  def getCountry: String = country

  def setCountry(newCountry: String): Unit = {
    country = newCountry
  }
}

object PersonApp {
  def main(args: Array[String]): Unit = {
    val person = new Person("Andrey Ira", 35, "France")

    println("Original Person:")
    println(s"Name: ${person.getName}")
    println(s"Age: ${person.getAge}")
    println(s"Country: ${person.getCountry}")

    person.setName("Lior Daniela")
    person.setAge(30)
    person.setCountry("Canada")

    println("\nUpdated Person:")
    println(s"Name: ${person.getName}")
    println(s"Age: ${person.getAge}")
    println(s"Country: ${person.getCountry}")
  }
}

Sample Output:

Original Person:
Name: Andrey Ira
Age: 35
Country: France

Updated Person:
Name: Lior Daniela
Age: 30
Country: Canada

Explanation:

In the above exercise,

The "Person" class has properties like name, age, and country defined using constructor parameters. The class also includes getter and setter methods for each property.

The getName, setName, getAge, setAge, getCountry, and setCountry methods allow you to retrieve and modify the properties' values.

The "PersonApp" object contains the main method, which demonstrates the "Person" class. It creates a "Person" object, prints its original values, updates the properties using the setter methods, and then prints the updated values.

Scala Code Editor :

Previous: Scala OOP Exercises Home.
Next: Create student subclass with grade property.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.