-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10_Inheritence.kt
71 lines (60 loc) · 1.53 KB
/
10_Inheritence.kt
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
fun main() {
// Single Inheritance
val dog = Dog("Bulldog")
dog.showSpecies()
dog.bark()
// Multilevel Inheritance
val labrador = Labrador("Labrador Retriever")
labrador.showSpecies()
labrador.bark()
labrador.swim()
// Hierarchical Inheritance
val cat = Cat("Persian")
cat.showSpecies()
cat.meow()
// Multiple Inheritance through interfaces
val flyingFish = FlyingFish("Flying Fish")
flyingFish.showSpecies()
flyingFish.swim()
flyingFish.fly()
}
// Base class
open class Animal(val species: String) {
fun showSpecies() {
println("Species: $species")
}
}
// Single Inheritance: Dog inherits from Animal
class Dog(species: String) : Animal(species) {
fun bark() {
println("--The dog barks!")
}
}
// Multilevel Inheritance: Labrador inherits from Dog, which inherits from Animal
class Labrador(species: String) : Dog(species) {
fun swim() {
println("--The Labrador swims!")
}
}
// Hierarchical Inheritance: Cat inherits from Animal
class Cat(species: String) : Animal(species) {
fun meow() {
println("--The cat meows!")
}
}
// Multiple Inheritance through interfaces
interface Swimmer {
fun swim()
}
interface Flyer {
fun fly()
}
class FlyingFish(species: String) : Animal(species), Swimmer, Flyer
//Kotlin doesn't support multiple , we can use interface classes
override fun swim() {
println("--The Flying Fish swims!")
}
override fun fly() {
println("--The Flying Fish flies!")
}
}