How do i create a class object in Kotlin

Published April 22, 2021

In this kotlin programming example we will learn how to create a class object in kotlin. we already know Class is an entity which acts as a blueprint of an Object. Object contains a state and behavior. Similar to java class in kotlin class can be declared as class header and a body which is enclosed by curly braces.

In this below kotlin programming example we will create a class of Employee which contains the properties of Name, Age, Salary.

To Create an Object for a class in kotlin we will not use "new" keyword like Java. we just use the class name with braces.

 

package com.rrtutors.lib

// Class declaration,
class Employee{
    //member variables of class
    private var name: String=""
    private var age: Int=0
    private var salary: Int=0

    //Member functions of class to set Employee name
    fun setEmployeeName(name:String){
        this.name=name
    }

    //Member functions of class to set Employee age
    fun setEmployeeAge(age:Int){
        this.age=age
    }
//Member functions of class to set Employee age
    fun setEmployeeSalary(salary:Int){
        this.salary=salary
    }

    //Member functions of class to return Employee details
    fun getEmployeeDetails():String{
        return "Name :  $name, Age : $age, Salary : $salary"
    }
}

//Main function, Entry Point of Program
fun main(args:Array<String>){
    //Create Object of Employee Class
    val employee1 = Employee() // There is no 'new' keyword

    // set Employee age and name to call member functions of class
    employee1.setEmployeeName("Tom")
    employee1.setEmployeeAge(30)
    employee1.setEmployeeSalary(30000)

    //print Employee details bt ccall getEmployeeDetails members functions
    println("Employee : ${employee1.getEmployeeDetails()}")

    //Create Second object of Employee class
    val employee2 = Employee()
    employee2.setEmployeeName("Michel Bhevan")
    employee2.setEmployeeAge(23)
    employee1.setEmployeeSalary(45000)
    println("Employee : ${employee2.getEmployeeDetails()}")
}

 

Here is the creation of the employee class object

val employee1 = Employee()

To set the properties of the employee object we will use the object employee1 reference.

 

Output:

Employee : Name :  Tom, Age : 30, Salary : 30000
Employee : Name :  Michel Bhevan, Age : 23, Salary : 0

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

814 Views