w3resource

Kotlin Class: Create and calculate rectangle area

Kotlin Class: Exercise-2 with Solution

Write a Kotlin program that creates a class 'Rectangle' with properties for width and height. Include a function to calculate the rectangle area.

Sample Solution:

Kotlin Code:

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

fun main() {
    val rectangle = Rectangle(7.0, 3.0)
    val area = rectangle.calculateArea()
    println("Rectangle Area: $area")
}

Sample Output:

Rectangle Area: 21.0

Explanation:

In the above exercise -

  • First we define a class "Rectangle" with two properties: width and height. The class also includes a function calculateArea() that multiplies the width and height to calculate the rectangle area.
  • In the main() function, we create an instance of the Rectangle class with a width of 7.0 and a height of 3.0. We then call the calculateArea() function on the rectangle object to calculate the area and store it in the area variable. The calculated area is then printed using println ().

Kotlin Editor:


Previous: Create and print person details.
Next: Create and display Car information.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.