Left Index

Kotlin Class and Object

As other languages like C++, C# or Java etc... Kotlin also have OOPs concept. Most important concept in OOPs is how you declare a class and every class has a state and a behaviour . State is generally represented by the data in the class and the behaviour by the functions .


Kotlin Class

We need to define a class before creating object and class keyword is used to define a class. The class declaration consist of class name, class header and class body enclosed with curly braces.

Syntax:
// 'class' keyword used to create class and 'Hello' is name of class
class ClassName {
	// body of class
	// contains properties
	
	// and member functions
}

Example:
class Student {
	val MALE: Int = 0
	val FEMALE: Int = 1
	
	var studentName: String = "Jony"
	var rollNo: Int = 23
	var gender: Int = MALE
	
	fun getStudentName() : String {
		return studentName
	}
	
	fun setStudentName(name: String) {
		studentName = name
	}
	
	fun getRollNo() = rollNo
	
	fun setRollNo(rollNo: Int) {
		this.rollNo = no
	}
	
	fun getGender() = gender
	
	fun setGender(gender: Int) {
		this.gender = gender
	}
}

Creating Object and Accessing Properties and Member Functions
package com.theitbulls.kotlinex

import java.util.ArrayList
import java.util.HashMap

fun main(args: Array<String>) {
	// creating object of Student class
	var student = Student()

	// accessing properties
	println("Student name: ${student.studentName}")
	println("Student Roll No.: ${student.rollNo}")
	if (student.gender == student.MALE) {
		println("Gender: Male")
	} else {
		println("Gender: Female")
	}

	println()
	// accessing member function
	student.printStudentDetail()
}

class Student {
	val MALE: Int = 0
	val FEMALE: Int = 1

	var studentName: String = "Jony"
	var rollNo: Int = 23
	var gender: Int = MALE

	fun printStudentDetail() {
		// accessing properties
		println("Student name: ${studentName}")
		println("Student Roll No.: ${rollNo}")
		if (gender == MALE) {
			println("Gender: Male")
		} else {
			println("Gender: Female")
		}
	}
}
Output:
Student name: Jony
Student Roll No.: 23
Gender: Male

Student name: Jony
Student Roll No.: 23
Gender: Male