Kotlin Class: Triangle class with perimeter calculation
Write a Kotlin program that creates a class 'Triangle' with side length properties. Include a function to calculate the triangle perimeter.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Classes in Kotlin: A class serves as a blueprint for creating objects with specific attributes and behaviors.
- Primary Constructor: It initializes the properties of an object when an instance of the class is created.
- Properties: Variables inside a class that store values such as side lengths of a triangle.
- Functions in Classes: Functions like calculatePerimeter() perform operations on class properties.
- Object Creation: Creating an instance of a class and calling its functions to perform operations.
Hints (Try Before Looking at the Solution!)
Try to solve the problem with these hints:
- Hint 1: Create a class named Triangle with three properties: side1, side2, and side3.
- Hint 2: Define a function named calculatePerimeter() inside the class.
- Hint 3: The function should return the sum of the three side lengths.
- Hint 4: In the main() function, create an instance of the Triangle class with sample side lengths.
- Hint 5: Call the calculatePerimeter() function on the created object and print the result.
Sample Solution:
Kotlin Code:
class Triangle(
val side1: Double,
val side2: Double,
val side3: Double
) {
fun calculatePerimeter(): Double {
return side1 + side2 + side3
}
}
fun main() {
val triangle = Triangle(5.0, 6.0, 7.0)
val perimeter = triangle.calculatePerimeter()
println("Triangle Perimeter: $perimeter")
}
Sample Output:
Triangle Perimeter: 18.0
Explanation:
In the above exercise -
- First we define a class "Triangle" with three properties: side1, side2, and side3, representing the lengths of the triangle's sides.
- The class includes a function "calculatePerimeter()" that calculates the perimeter of the triangle by summing the lengths of all three sides.
- In the main() function, we create an instance of the Triangle class named triangle with side lengths 5.0, 6.0, and 7.0. We then call the "calculatePerimeter()" function on the triangle object and store the result in the perimeter variable.
- Using the println function, we print the perimeter calculated.
Kotlin Editor:
Previous: Employee class with details display.
Next: Calculate the total cost of a product.
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