w3resource

Scala Program: Create student subclass with grade property

Scala OOP Exercise-2 with Solution

Write a Scala program that creates a subclass Student that extends the Person class. Add a property called grade and implement methods to get and set it.

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
  }
}

class Student(name: String, age: Int, country: String, var grade: String)
  extends Person(name, age, country) {

  def getGrade: String = grade

  def setGrade(newGrade: String): Unit = {
    grade = newGrade
  }
}

object StudentApp {
  def main(args: Array[String]): Unit = {
    val student = new Student("Saturnino Nihad", 18, "USA", "A")

    println("Original Student:")
    println(s"Name: ${student.getName}")
    println(s"Age: ${student.getAge}")
    println(s"Country: ${student.getCountry}")
    println(s"Grade: ${student.getGrade}")

    student.setName("Albino Ellen")
    student.setAge(20)
    student.setCountry("Canada")
    student.setGrade("B")

    println("\nUpdated Student:")
    println(s"Name: ${student.getName}")
    println(s"Age: ${student.getAge}")
    println(s"Country: ${student.getCountry}")
    println(s"Grade: ${student.getGrade}")
  }
}

Sample Output:

Original Student:
Name: Saturnino Nihad
Age: 18
Country: USA
Grade: A

Updated Student:
Name: Albino Ellen
Age: 20
Country: Canada
Grade: B

Explanation:

In the above exercise -

The "Person" class defines the properties name, age, and country, along with the corresponding getter and setter methods.

The "Student" class extends the Person class and adds an additional property called grade. It also includes getter and setter methods specific to the grade property.

The StudentApp object contains the main method, which demonstrates the Student class usage. It creates a Student object, prints its original values, updates the properties using the setter methods inherited from the Person class and the setGrade method from the Student class. It then prints the updated values.

Scala Code Editor :

Previous: Create a Person class with properties and methods.
Next: Calculate the factorial with MathUtils Object.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.