Kotlin Class: Person class with nested ContactInfo class
Kotlin Class: Exercise-15 with Solution
Write a Kotlin program that creates a class 'Person' with a nested class 'ContactInfo' to store the person's contact information.
Sample Solution:
Kotlin Code:
class Person(val name: String) {
private var contactInfo: ContactInfo? = null
fun setContactInfo(email: String, phone: String) {
contactInfo = ContactInfo(email, phone)
}
fun displayContactInfo() {
contactInfo?.let {
println("Contact Information:")
println("Email: ${it.email}")
println("Phone: ${it.phone}")
}
}
inner class ContactInfo(val email: String, val phone: String)
}
fun main() {
val person = Person("Mitko Leida")
person.setContactInfo("[email protected]", "01234567")
person.displayContactInfo()
}
Sample Output:
Contact Information: Email: [email protected] Phone: 01234567
Explanation:
In the above exercise -
- First we define a "Person" class with a nested class "ContactInfo". The "Person" class has a name property and a nullable contactInfo property of type ContactInfo.
- The "setContactInfo()" function sets the person's contact information. It takes email and phone as parameters and creates an instance of the nested ContactInfo class to store the information.
- The "displayContactInfo()" function displays the person's contact information. It checks if the contactInfo property is not null and prints the email and phone.
- Inside the "ContactInfo" class, we have email and phone properties that store contact information.
- In the main function, we create an instance of the Person class and set the contact information using the "setContactInfo()" function. We call the "displayContactInfo()" function to print the contact information.
Kotlin Editor:
Previous: Shape, circle, and rectangle classes with area calculation.
Next: Logger class with companion object for logging.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics