Introduction to polymorphism using a horticultural example.
```kotlin
// Botanical Gardens Management System
// Demonstrating how polymorphism naturally models real-world hierarchies // Base class representing fundamental plant characteristics
open class Plant(
val scientificName: String,
val commonName: String,
protected var heightInCm: Double,
protected var healthStatus: String
) {
open fun water() {
println("Basic watering procedure for $commonName")
}
open fun prune() {
println("Basic pruning procedure for $commonName")
}
open fun fertilize() {
println("Basic fertilizing procedure for $commonName")
}
open fun displayCareInstructions() {
println("Basic care instructions for $commonName ($scientificName)")
}
} // Specialized class for tropical plants
class TropicalPlant(
scientificName: String,
commonName: String,
heightInCm: Double,
healthStatus: String,
private val humidityRequired: Int,
private val minimumTemp: Double
) : Plant(scientificName, commonName, heightInCm, healthStatus) {
override fun water() {
println("Misting $commonName to maintain $humidityRequired% humidity")
println("Ensuring soil remains consistently moist but not waterlogged")
}
override fun displayCareInstructions() {
println("=== Tropical Plant Care: $commonName ===")
println("Scientific Name: $scientificName")
println("Required Humidity: $humidityRequired%")
println("Minimum Temperature: $minimumTemp°C")
println("Needs regular misting and humid conditions")
}
} // Specialized class for desert plants
class DesertPlant(
scientificName: String,
commonName: String,
heightInCm: Double,
healthStatus: String,
private val droughtTolerance: String,
private val sandContent: Int
) : Plant(scientificName, commonName, heightInCm, healthStatus) {
override fun water() {
println("Minimal watering for $commonName - checking soil dryness first")
println("Using specialized desert plant watering technique")
}
override fun displayCareInstructions() {
println("=== Desert Plant Care: $commonName ===")
println("Scientific Name: $scientificName")
println("Drought Tolerance: $droughtTolerance")
println("Required Sand Content: $sandContent%")
println("Allow soil to dry completely between waterings")
}
} // Specialized class for alpine plants
class AlpineFlora(
scientificName: String,
commonName: String,
heightInCm: Double,
healthStatus: String,
private val minimumAltitude: Int,
private val frostResistant: Boolean
) : Plant(scientificName, commonName, heightInCm, healthStatus) {
override fun water() {
println("Careful watering for $commonName - ensuring good drainage")
println("Using specialized alpine watering technique to prevent root rot")
}
override fun displayCareInstructions() {
println("=== Alpine Plant Care: $commonName ===")
println("Scientific Name: $scientificName")
println("Minimum Altitude: ${minimumAltitude}m")
println("Frost Resistant: $frostResistant")
println("Requires excellent drainage and protection from excessive moisture")
}
} // Horticulturist class demonstrating polymorphic plant care
class Horticulturist(val name: String, val specialization: String) {
fun providePlantCare(plant: Plant) {
println("\n$name ($specialization) is tending to the plant:")
plant.displayCareInstructions()
plant.water()
plant.prune()
plant.fertilize()
}
} // Botanical Garden management demonstrating the power of polymorphism
class BotanicalGarden {
private val plants = mutableListOf<Plant>()
private val horticulturists = mutableListOf<Horticulturist>()
fun addPlant(plant: Plant) {
plants.add(plant)
}
fun addHorticulturist(horticulturist: Horticulturist) {
horticulturists.add(horticulturist)
}
fun performDailyCare() {
println("\n=== Daily Care Routine Starting ===\n")
plants.forEach { plant ->
// Find appropriate specialist for the plant type
val specialist = when (plant) {
is TropicalPlant -> horticulturists.find { it.specialization == "Tropical" }
is DesertPlant -> horticulturists.find { it.specialization == "Desert" }
is AlpineFlora -> horticulturists.find { it.specialization == "Alpine" }
else -> horticulturists.firstOrNull()
}
specialist?.providePlantCare(plant) ?: println("No specialist available for this plant type")
}
}
} fun main() {
println("""
Welcome to the Polymorphic Botanical Gardens!
In our gardens, we demonstrate how object-oriented programming naturally
mirrors the real world. Just as plants have evolved to thrive in different
environments, our code evolves to handle different types of plants efficiently.
Watch as our specialized horticulturists care for various plants:
""".trimIndent())
val garden = BotanicalGarden()
// Adding different types of plants
garden.addPlant(TropicalPlant(
"Strelitzia reginae",
"Bird of Paradise",
150.0,
"Healthy",
80,
18.0
))
garden.addPlant(DesertPlant(
"Ferocactus wislizeni",
"Fishhook Barrel Cactus",
60.0,
"Excellent",
"High",
90
))
garden.addPlant(AlpineFlora(
"Leontopodium alpinum",
"Edelweiss",
15.0,
"Good",
2000,
true
))
// Adding specialized horticulturists
garden.addHorticulturist(Horticulturist("Maria", "Tropical"))
garden.addHorticulturist(Horticulturist("Ahmed", "Desert"))
garden.addHorticulturist(Horticulturist("Hans", "Alpine"))
// Perform daily care routine
garden.performDailyCare()
} This example demonstrates several key benefits of polymorphism: 1. **Natural Modeling**: Just as real plants share common characteristics but require specialized care, our Plant hierarchy models this through inheritance and polymorphism. 2. **Code Reusability**: The base Plant class provides common functionality that specialized plants can inherit and modify as needed. 3. **Extensibility**: New plant types can be easily added by creating new classes that inherit from Plant, without changing existing code. 4. **Simplified Management**: The BotanicalGarden class can treat all plants uniformly through their common interface while still providing specialized care. 5. **Type Safety**: The compiler ensures that all plant types implement required functionality, preventing errors. The example shows how polymorphism allows us to:
- Write code that works with objects at different levels of abstraction
- Handle specialized cases without complex conditional logic
- Create maintainable and scalable systems
- Model real-world relationships effectively Challenge thinking for students:
1. Add more specialized plant types with unique care requirements
2. Include additional garden management features
3. Add more complex interactions between plants and horticulturists