Kotlin Class: Employee class with details display
Write a Kotlin program that creates a class 'Employee' with properties for name, age, and designation. Include a function to display employee details.
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 functions.
- 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 name, age, and designation.
- Functions in Classes: Functions like displayDetails() can be used to display information about an object.
- 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 Employee with three properties: name, age, and designation.
- Hint 2: Define a function named displayDetails() inside the class.
- Hint 3: The function should print the employee’s name, age, and designation.
- Hint 4: In the main() function, create an instance of the Employee class with sample values.
- Hint 5: Call the displayDetails() function on the created object to print employee details.
Sample Solution:
Kotlin Code:
class Employee(
val name: String,
val age: Int,
val designation: String
) {
fun displayDetails() {
println("Name: $name")
println("Age: $age")
println("Designation: $designation")
}
}
fun main() {
val employee = Employee("Herais Lochlainn", 35, "Manager")
employee.displayDetails()
}
Sample Output:
Name: Herais Lochlainn Age: 35 Designation: Manager
Explanation:
In the above exercise -
- First we define a class "Employee" with three properties: name, age, and designation. The class includes a function "displayDetails()" that prints employee details, including name, age, and designation.
- In the "main()" function, we create an instance of the "Employee" class named employee with the name "Bryce Clark", age 30, and designation "Manager". We then call the displayDetails function on the employee object, which prints the employee details to the console.
Kotlin Editor:
Previous: Circle class with circumference calculation.
Next: Triangle class with perimeter calculation.
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