Kotlin Class: Calculate the total cost of a product
Write a Kotlin program that creates a class 'Product' with properties for name, price, and quantity. Calculate the total cost of the product with a function.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Classes in Kotlin: A class is a blueprint for creating objects with specific properties and behaviors.
- Primary Constructor: It is used to initialize the properties of a class when an instance is created.
- Properties: Variables within a class that store values such as name, price, and quantity of a product.
- Functions in Classes: Functions like calculateTotalCost() perform calculations using class properties.
- Object Creation: Creating an instance of a class and calling its functions to compute results.
Hints (Try Before Looking at the Solution!)
Try to solve the problem with these hints:
- Hint 1: Create a class named Product with properties for name, price, and quantity.
- Hint 2: Define a function named calculateTotalCost() inside the class.
- Hint 3: The function should return the product of price and quantity.
- Hint 4: In the main() function, create an instance of the Product class with sample values.
- Hint 5: Call the calculateTotalCost() function on the created object and print the result.
Sample Solution:
Kotlin Code:
class Product(
val name: String,
val price: Double,
val quantity: Int
) {
fun calculateTotalCost(): Double {
return price * quantity
}
}
fun main() {
val product = Product("Desktop", 2000.0, 4)
val totalCost = product.calculateTotalCost()
println("Total Cost: $totalCost")
}
Sample Output:
Total Cost: 8000.0
Explanation:
In the above exercise -
- In this program, we define a class "Product" with three properties: name, price, and quantity, representing the product's name, price, and quantity.
- The class includes a function "calculateTotalCost()" that calculates the total cost of the product by multiplying the price by the quantity.
- In the "main()" function, we create an instance of the Product class named product with the name "Desktop", a price of 2000.0, and a quantity of 4. We then call the calculateTotalCost function on the product object and store the result in the totalCost variable.
- The println function is used to print the total cost calculated.
Kotlin Editor:
Previous: Triangle class with perimeter calculation.
Next: Create an Animal class and make animal sounds.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.