Exercise: Implementing the Product Class
Enhance your Kotlin skills by creating and handling product information with custom setters and methods.
We'll cover the following
Problem statement
Your task is to include the necessary properties and functionalities according to the instructions below:
Implement the
Product
class with the following properties:name
(String
): Representing the product’s nameprice
(Double
): Indicating the product’s pricequantity
(Int
): Denoting the initial quantity of the product
Create a custom setter for the
quantity
property, ensuring that negative values are automatically set to zero.Introduce a method called
calculateTotalValue
within theProduct
class to compute and return the total value of the product. The total value is defined as the product of quantity and price.Example: If the product quantity is 3, and the price is 100, the function should return 300.
Implement a method named
restock
in theProduct
class, allowing an increase in the product’s quantity by a specified positive amount. The method should take the restock quantity as an argument. If a negative value is specified, the method should have no effect.
Tips:
Use the
field
keyword in the custom setter to modify the backing field.Calculate the total value by multiplying
price
andquantity
.
Instructions
In the provided code, you are provided with the initial structure of a Product
class designed to represent a retail product. Your task is to complete the functionality of this class by following the above instructions:
The actual output when running the provided code should be as follows:
Get hands-on with 1400+ tech skills courses.