-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstraction
34 lines (27 loc) · 862 Bytes
/
Abstraction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
abstract class Animal(val name: String) {
abstract fun makeSound()
}
class Dog(name: String) : Animal(name) {
override fun makeSound() {
println("The dog is barking")
}
}
class Cat(name: String) : Animal(name) {
override fun makeSound() {
println("The cat is meowing")
}
}
fun main() {
val dog = Dog("Buddy")
val cat = Cat("Kitty")
val animals = arrayOf(dog, cat)
for (animal in animals) {
animal.makeSound()
}
}
/
In this example, the Animal class is an abstract class that has an abstract method called makeSound().
The Dog and Cat classes are derived from the Animal class and they implement the makeSound() method.
The main() function creates an array of animals that contains both dogs and cats.
The for loop iterates over each animal in the array and calls its makeSound() method.
/