Kotlin Class: Create an Animal class and make animal sounds
Write a Kotlin program that creates a class 'Animal' with properties for name and sound. Include a function to make the animal's sound.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Classes in Kotlin: A class is a template for creating objects with specific attributes and behaviors.
- Primary Constructor: Used to initialize class properties when an object is created.
- Properties: Variables inside a class that store values like an animal’s name and sound.
- Functions in Classes: Functions such as makeSound() define behaviors of the class.
- Object Creation: Creating instances of a class and calling its methods to perform actions.
Hints (Try Before Looking at the Solution!)
Try to solve the problem using these hints:
- Hint 1: Define a class named Animal with properties for name and sound.
- Hint 2: Inside the class, create a function called makeSound() that prints the animal's name along with its sound.
- Hint 3: In the main() function, create instances of the Animal class with different names and sounds.
- Hint 4: Call the makeSound() function for each object to display its 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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics