w3resource

Kotlin Factory method pattern: Creating animal instances

Kotlin OOP Program: Exercise-5 with Solution

Write a Kotlin object-oriented program that implements the factory method pattern by creating an abstract class Animal with subclasses Tiger and Lion. Use a factory class to create instances of animals based on user input.

Sample Solution:

Kotlin Code:

abstract class Animal {
    abstract fun makeSound()
}

class Tiger : Animal() {
    override fun makeSound() {
        println("Tiger: Roar!")
    }
}

class Lion : Animal() {
    override fun makeSound() {
        println("Lion: Roar!")
    }
}

class AnimalFactory {
    fun createAnimal(type: String): Animal? {
        return when (type) {
            "Tiger" -> Tiger()
            "Lion" -> Lion()
            else -> null
        }
    }
}

fun main() {
    val animalFactory = AnimalFactory()
    val userInput = "Lion"
    //val userInput = "Tiger"
    println("Type of animal (Tiger or Lion): $userInput")
    
    val animal = animalFactory.createAnimal(userInput.orEmpty())
    animal?.makeSound()
}

Sample Output:

Type of animal (Tiger or Lion): Lion
Lion: Roar!

Explanation:

In the above exercise -

  • First, we create an abstract class "Animal" that defines common behavior. It has an abstract method makeSound().
  • The "Tiger" and "Lion" classes are subclasses of Animal and provide their own implementations of the "makeSound()" method.
  • The "AnimalFactory" class acts as a factory class. It has a method "createAnimal()" that takes a type (user input) and returns an instance of the corresponding animal. In this case, it creates instances of Tiger and Lion based on user input.
  • In the main() function, we create an AnimalFactory instance. We prompt the user to enter the type of animal they want to make. Based on user input, we use the factory class to generate an animal object. We then call the makeSound() method on the created animal object to demonstrate its behavior.

Kotlin Editor:


Previous: Modifying component behavior.
Next: Implementing subscription events.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.