Kotlin program | Example of class and object (with student data)

Kotlin | Student Class Example: Here, we are implementing a Kotlin program to demonstrate the example of class and object (with student data).
Submitted by IncludeHelp, on June 03, 2020

In the below program, we are creating a student class to input and print the student data like name, age. It is a simple example of creating class in Kotlin.

Note:

  • The compiler creates a default constructor if we do not declare a constructor.
  • Class properties must be initialized.

Program for student class in Kotlin

package com.includehelp

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

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

    //Member functions of class to set student age
    fun setStudentAge(age:Int){
        this.age=age
    }

    //Member functions of class to return student details
    fun getStudentDetails():String{
        return "Name :  $name, Age : $age"
    }
}

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

    // set Student age and name to call member functions of class
    student1.setStudentName("Mike")
    student1.setStudentAge(30)

    //print Student details bt ccall getStudentDetails members functions
    println("Student : ${student1.getStudentDetails()}")

    //Create Second object of student class
    val student2 = Student()
    student2.setStudentName("Irina")
    student2.setStudentAge(23)
    println("Student : ${student2.getStudentDetails()}")
}

Output:

Student : Name :  Mike, Age : 30
Student : Name :  Irina, Age : 23


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.