w3resource

Kotlin OOP Program: Shape base class and Polymorphic subclasses

Kotlin OOP Program: Exercise-1 with Solution

Write a Kotlin object-oriented program that creates a base class Shape and derives subclasses Circle, Rectangle, and Triangle. Implement appropriate methods in each class and demonstrate polymorphism.

Sample Solution:

Kotlin Code:

abstract class Shape {
    abstract fun area(): Double
    abstract fun perimeter(): Double
}

class Circle(private val radius: Double) : Shape() {
    override fun area(): Double {
        return Math.PI * radius * radius
    }

    override fun perimeter(): Double {
        return 2 * Math.PI * radius
    }
}

class Rectangle(private val width: Double, private val height: Double) : Shape() {
    override fun area(): Double {
        return width * height
    }

    override fun perimeter(): Double {
        return 2 * (width + height)
    }
}

class Triangle(private val side1: Double, private val side2: Double, private val side3: Double) : Shape() {
    override fun area(): Double {
        val semiPerimeter = perimeter() / 2
        return Math.sqrt(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (semiPerimeter - side3))
    }

    override fun perimeter(): Double {
        return side1 + side2 + side3
    }
}

fun main() {
    val circle = Circle(4.5)
    val rectangle = Rectangle(7.0, 11.0)
    val triangle = Triangle(4.0, 5.0, 6.0)

    val shapes = listOf(circle, rectangle, triangle)

    for (shape in shapes) {
        println("Area: ${shape.area()}")
        println("Perimeter: ${shape.perimeter()}")
        println()
    }
}

Sample Output:

Area: 63.61725123519331
Perimeter: 28.274333882308138

Area: 77.0
Perimeter: 36.0

Area: 9.921567416492215
Perimeter: 15.0

Explanation:

In the above exercise -

  • The "Shape" class is declared as an abstract class with two abstract methods: "area()" and "perimeter()". The Circle, Rectangle, and Triangle classes inherit from the "Shape" class and provide their own implementations of these methods.
  • In the "main()" function, instances of Circle, Rectangle, and Triangle are created and stored in a list. Using a loop, the program demonstrates polymorphism by calling the area() and perimeter() methods on each shape object. This dynamically invokes the appropriate implementation based on the actual object type.
  • The output of the program will display the area and perimeter of each shape.

Kotlin Editor:


Previous: Kotlin OOP Exercises Home.
Next: Implementing a logger for logging functionality.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/oop/kotlin-oop-exercise-1.php