Kotlin Class and Object

In this tutorial, we will learn all about Classes and Objects in Kotlin with examples.

A class is a blueprint/template for creating objects of similar type. The objects contain states in the form of member variables (properties) and behavior in the form of member functions (methods). 

Kotlin Class

You can create a Class in Kotlin using the class keyword.

Kotlin- Create Class Example

In this example, we will create a User class in Kotlin with properties firstName and lastName.
package net.javaguides.kotlin.examples

class User {
    // Properties or Member Variables
    var firstName: String;
    var lastName: String;

    // Secondary Constructor
    constructor(firstName: String, lastName: String) {
        this.firstName = firstName
        this.lastName = lastName
    }
}

fun main(args: Array < String > ) {
    val person = User("Tony", "Stark")
    println(person.firstName) // Tony
    println(person.lastName) // Stark
}
Output:
Tony
Stark

Kotlin Class Functions

In Kotlin class, we can create functions to perform certain actions:
class Car(var brand: String, var model: String, var year: Int) {
  // Class function
  fun drive() {
    println("Wrooom!")
  }
  
  // Class function with parameters
  fun speed(maxSpeed: Int) {
    println("Max speed is: " + maxSpeed)
  }
}

fun main() {
  val c1 = Car("Ford", "Mustang", 1969)
  
  // Call the functions
  c1.drive()
  c1.speed(200)
}

Output:

Ford Mustang 1969
Wrooom!
Max speed is: 200
When a function is declared inside a class, it is known as a class function or member function. When an object of the class is created, it has access to all of the class functions.

Kotlin Nested Class

A nested class is a class that is created inside another class. In Kotlin, the nested class is by default static, so its data member and member function can be accessed without creating an object of a class. The nested class cannot be able to access the data member of the outer class.

Kotlin Nested Class Example:

package net.javaguides.kotlin

class outerClass {
    private
    var name: String = "outerClass"

    class nestedClass {
        var description: String = "code inside nested class"
        private
        var id: Int = 101
        fun foo() {
            //  print("name is ${name}") // cannot access the outer class member  
            println("Id is ${id}")
        }
    }
}

fun main(args: Array < String > ) {
    // nested class must be initialize  
    println(outerClass.nestedClass().description) // accessing property  
    var obj = outerClass.nestedClass() // object creation  
    obj.foo() // access member function  
}
Output:
code inside nested class
Id is 101

Kotlin Abstract Class

A class that is declared with an abstract keyword is known as an abstract class. An abstract class cannot be instantiated. This means we cannot create an object of an abstract class. The method and properties of an abstract class are non-abstract unless they are explicitly declared as abstract.

Declaration of abstract class

Abstract classes are partially defined classes, methods, and properties which are not implemented but must be implemented into the derived class.
abstract class A {  
var x = 0  
    abstract fun doSomething()  
}  

Kotlin Abstract Class Example

In this example, an abstract class Bank that contains an abstract function simpleInterest() accepts three parameters principlerate, and time. The class SBI and PNB provides the implementation of simpleInterest() function and returns the result.
package net.javaguides.kotlin.examples

abstract class Bank {
    abstract fun simpleInterest(principle: Int, rate: Double, time: Int): Double
}

class SBI: Bank() {
    override fun simpleInterest(principle: Int, rate: Double, time: Int): Double {
        return (principle * rate * time) / 100
    }
}

class PNB: Bank() {
    override fun simpleInterest(principle: Int, rate: Double, time: Int): Double {
        return (principle * rate * time) / 100
    }
}

fun main(args: Array < String > ) {
    var sbi: Bank = SBI()
    val sbiint = sbi.simpleInterest(1000, 5.0, 3)
    println("SBI interest is $sbiint")
    var pnb: Bank = PNB()
    val pnbint = pnb.simpleInterest(1000, 4.5, 3)
    println("PNB interest is $pnbint")
}
Output:
SBI interest is 150.0
PNB interest is 135.0

Kotlin Inheritance

Inheritance allows inheriting the feature of an existing class (or base or parent class) to a new class (or derived class or child class).

The concept of inheritance is allowed when two or more classes have the same properties. It allows code reusability. A derived class has only one base class but may have multiple interfaces whereas a base class may have one or more derived classes.

In Kotlin, the derived class inherits a base class using the : operator in the class header (after the derived class name or constructor).
open class Base(p: Int){  
  
}  
class Derived(p: Int) : Base(p){  
  
}  

Kotlin Inheritance Example

package net.javaguides.kotlin.examples

open class Employee(name: String, age: Int, salary: Float) {
    init {
        println("Name is $name.")
        println("Age is $age")
        println("Salary is $salary")
    }
}

class Programmer(name: String, age: Int, salary: Float): Employee(name, age, salary) {
    fun doProgram() {
        println("programming is my passion.")
    }
}

class Salesman(name: String, age: Int, salary: Float): Employee(name, age, salary) {
    fun fieldWork() {
        println("travelling is my hobby.")
    }
}

fun main(args: Array < String > ) {
    val obj1 = Programmer("Ramesh", 25, 40000 f)
    obj1.doProgram()
    val obj2 = Salesman("Vijay", 24, 30000 f)
    obj2.fieldWork()
}
Output:
Name is Ramesh.
Age is 25
Salary is 40000.0
programming is my passion.
Name is Vijay.
Age is 24
Salary is 30000.0
travelling is my hobby.

Kotlin open keyword

As Kotlin classes are final by default, they cannot be inherited simply. We use the open keyword before the class to inherit a class and make it non-final. 

For example:
open class Employee(name: String, age: Int, salary: Float) {
    init {
        println("Name is $name.")
        println("Age is $age")
        println("Salary is $salary")
    }
}

Comments