w3resource

Kotlin Class: Create an Animal class and make animal sounds

Kotlin Class: Exercise-11 with Solution

Write a Kotlin program that creates a class 'Animal' with properties for name and sound. Include a function to make the animal's sound.

Sample Solution:

Kotlin Code:

class Animal(
    val name: String,
    val sound: String
) {
    fun makeSound() {
        println("$name makes the sound: $sound")
    }
}

fun main() {
    val tiger = Animal("Tiger", "Roar!")
    val lion = Animal("Lion", "Growls!")
    
    tiger.makeSound()
    lion.makeSound()
}

Sample Output:

Tiger makes the sound: Roar!
Lion makes the sound: Growls!

Explanation:

In the above exercise -

  • We define a class "Animal" with two properties: name and sound, representing the animal's name and sound.
  • The class includes a function makeSound that prints the animal's name along with its sound.
  • In the main() function, we create two instances of the Animal class: tiger with the name "Tiger" and sound "Roar!", and lion with the name "Lion" and sound "Growls!".
  • We then call the makeSound function on both tiger and lion objects. This prints the animal's name along with its sound using the println function.

Kotlin Editor:


Previous: Calculate the total cost of a product.
Next: Create Customer class and send welcome email.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



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/kotlin-exercises/class/kotlin-class-exercise-11.php