Kotlin Class: Create and calculate rectangle area
Write a Kotlin program that creates a class 'Rectangle' with properties for width and height. Include a function to calculate the rectangle area.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Classes in Kotlin: In Kotlin, a class is a blueprint for creating objects that encapsulate data and behavior. You can define properties and methods within a class.
- Constructors: A constructor is used to initialize the properties of a class when an object is created. In Kotlin, you can define a primary constructor directly in the class header.
- Methods in classes: Methods (functions) inside a class can operate on the properties of the class. In this case, a method will calculate the area using the properties width and height.
- Working with numbers: In this exercise, you will work with Double values to represent dimensions and calculate the area of a rectangle.
Hints (Try Before Looking at the Solution!)
Try to solve the problem with these hints:
- Hint 1: Create a class called Rectangle with two properties: width and height.
- Hint 2: Define a function inside the class to calculate the area. The area is calculated by multiplying the width and height.
- Hint 3: In the main() function, create an instance of the Rectangle class and pass the values for width and height.
- Hint 4: Call the method calculateArea() to compute the area and print the result.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics