w3resource

Kotlin Class: Shape, circle, and rectangle classes with area calculation

Kotlin Class: Exercise-14 with Solution

Write a Kotlin program that creates a class 'Shape' with an abstract function to calculate the area. Create subclasses 'Circle' and 'Rectangle' that override the area calculation function.

Sample Solution:

Kotlin Code:

abstract class Shape {
    abstract fun calculateArea(): Double
}

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

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

fun main() {
    val circle = Circle(7.0)
    val circleArea = circle.calculateArea()
    println("Circle Area: $circleArea")

    val rectangle = Rectangle(5.0, 7.0)
    val rectangleArea = rectangle.calculateArea()
    println("Rectangle Area: $rectangleArea")
}

Sample Output:

Circle Area: 153.93804002589985
Rectangle Area: 35.0

Explanation:

In the above exercise -

  • First we define an abstract class "Shape" with an abstract function "calculateArea()". This function does not have an implementation in the "Shape" class and must be overridden in its subclasses.
  • We create two subclasses: Circle and Rectangle. The Circle class takes the radius as a constructor parameter and overrides the "calculateArea()" function to calculate the area of the circle using the formula π * radius^2.
  • Similarly, the "Rectangle" class takes width and height as constructor parameters and overrides the "calculateArea()" function to calculate the area of the rectangle using the formula width * height.
  • In the main function, we create instances of Circle and Rectangle and call the "calculateArea()" function on each of them to calculate their respective areas. The calculated areas are then printed.

Kotlin Editor:


Previous: MathUtils class with static functions.
Next: Person class with nested ContactInfo class.

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/class/kotlin-class-exercise-14.php