w3resource

Scala Program: Animal class with make sound method

Scala OOP Exercise-8 with Solution

Write a Scala program that creates a class Animal with properties name and sound. Implement a method makeSound that prints the animal's sound.

Sample Solution:

Scala Code:

class Animal(val name: String, val sound: String) {
  def makeSound(): Unit = {
    println(s"The $name makes the sound: $sound")
  }
}

object AnimalApp {
  def main(args: Array[String]): Unit = {
    val cat = new Animal("Lion", "Roar")
    val dog = new Animal("Tiger", "Growl")
    
    cat.makeSound()
    dog.makeSound()
  }
}

Sample Output:

The Lion makes the sound: Roar
The Tiger makes the sound: Growl

Scala Code Editor :

Previous: Car class with information display method.
Next: Triangle class with equilateral check.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.