-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12_abstraction.kt
66 lines (55 loc) · 1.55 KB
/
12_abstraction.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
fun main() {
// Using abstraction with an abstract class
val circle: Shape = Circle(5.0)
println("Circle Area: ${circle.area()}")
circle.displayShape()
val rectangle: Shape = Rectangle(4.0, 6.0)
println("Rectangle Area: ${rectangle.area()}")
rectangle.displayShape()
// Using abstraction with an interface
val petrolCar = PetrolCar()
petrolCar.refuel()
petrolCar.startEngine()
val electricCar = ElectricCar()
electricCar.refuel()
electricCar.startEngine()
}
// Abstract class
abstract class Shape {
abstract fun area(): Double // Abstract method
// Non-abstract method
fun displayShape() {
println("This is a shape")
}
}
// Subclass Circle implementing the abstract method
class Circle(private val radius: Double) : Shape() {
override fun area(): Double {
return Math.PI * radius * radius
}
}
// Subclass Rectangle implementing the abstract method
class Rectangle(private val width: Double, private val height: Double) : Shape() {
override fun area(): Double {
return width * height
}
}
// Interface
interface Vehicle {
fun refuel() // Abstract method
fun startEngine() { // Non-abstract method (default implementation)
println("Engine started")
}
}
// Class implementing the interface
class PetrolCar : Vehicle {
override fun refuel() {
println("Petrol car refueling...")
}
}
// Class implementing the interface
class ElectricCar : Vehicle {
override fun refuel() {
println("Electric car charging...")
}
}