Scala Program: Class ContactInfo and customer with composition
Scala OOP Exercise-14 with Solution
Write a Scala program that creates a class ContactInfo with properties name, email, and address. Create a class Customer that includes a ContactInfo object.
Sample Solution:
Scala Code:
class ContactInfo(val name: String, val email: String, val address: String)
class Customer(val contactInfo: ContactInfo)
object CustomerApp {
def main(args: Array[String]): Unit = {
val contact = new ContactInfo("Serafim Eline", "[email protected]", "11 Open Street")
val customer = new Customer(contact)
println(s"Customer Name: ${customer.contactInfo.name}")
println(s"Customer Email: ${customer.contactInfo.email}")
println(s"Customer Address: ${customer.contactInfo.address}")
}
}
Sample Output:
Customer Name: Serafim Eline Customer Email: [email protected] Customer Address: 11 Open Street
Explanation:
In the above exercise,
- The "ContactInfo" class is defined with the properties name, email, and address. It has a primary constructor that takes these properties as parameters.
- The "Customer" class is defined by the property contactInfo of type ContactInfo. It represents a customer and includes contact information.
- The CustomerApp object contains the main method to test functionality. It creates an instance of the ContactInfo class with sample information and then creates a Customer object using the ContactInfo instance.
- Finally, the program prints the customer's name, email, and address using string interpolation.
Scala Code Editor :
Previous: Enum class for object color representation.
Next: Shape class with nested dimensions.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/scala-exercises/oop/scala-oop-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics