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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/oop/scala-oop-exercise-8.php