Recall the 2D shapes example we discussed in Interface :
interface Shape {
fun area(): Int
fun perimeter(): Int
fun summary(): String
}
class Square(
val side: Int
): Shape {
override fun area() = side * side
override fun perimeter() = 4 * side
override fun summary(): String {
return buildString {
append("Square")
append("(side = $side)")
append(": Area = ${area()}, ")
append("Perimeter = ${perimeter()}")
}
}
}
class Circle(
val r: Int
): Shape {
override fun area() = (Math.PI * r * r).toInt()
override fun perimeter() = (2 * Math.PI * r).toInt()
override fun summary(): String {
return buildString {
append("Circle")
append("(r = $r)")
append(": Area = ${area()}, ")
append("Perimeter = ${perimeter()}")
}
}
}
Notice that the summary()
function is similar in all implementations except the shape name & dimensions. Rest of the code is duplicated. We can further improve this program using Abstract class. summary()
function can be lifted up in Shape interface. It can use another new function dimensions()
that will return the dimensions string of a shape :
abstract class Shape {
abstract fun dimensions(): String
abstract fun area(): Int
abstract fun perimeter(): Int
fun summary(): String {
return buildString {
append(this@Shape.javaClass.simpleName)
append("(${dimensions()})")
append(": Area = ${area()}, ")
append("Perimeter = ${perimeter()}")
}
}
}
Note :
- We lifted up the
summary()
function in Shape interface. Because it had to defined, we are now using abstract class. Rest of the functions are abstract.
- A new function
dimensions()
is added, which is used by summary()
function get the dimensions string of the shape.
- To get the name of implementing class, we have used the syntax -
this@Shape.javaClass.simpleName
. It returns the name of class corresponding to this
.
Implementing the Shape abstract class :
class Rectangle(
val l: Int, val b: Int
): Shape() {
override fun dimensions() = "l = $l, b = $b"
override fun area() = l * b
override fun perimeter() = 2 * (l + b)
}
Now that summary()
function is lifted up, the code for derived classes is reduced.