Classes, Objects, Modifiers and Interfaces in Kotlin Tutorial

 

Kotlin is Object Oriented Programming language and it has all features of OOP.

It also supports functional programming like lambdas and higher-order functions.

since its Object Oriented so we have Classes in Kotlin, and those Classes have Objects, which are instances of Classes in Kotlin.

In this article, we will cover:-

  • Kotlin Classes and Kotlin Interfaces.
  • Kotlin Open, final and abstract modifiers.

Kotlin Classes

Let us first understand what are Classes in Kotlin.

A Class in Kotlin is a user-defined data type which can have properties and member functions inside the body of a Class.

Declaring Class in Kotlin

To declare a class in Kotlin

we simply write class <Keyword> ClassName<Name of the Class>

class ClassName {

   // inside body of a class, we can declare:
     
  //  properties
  //  member functions
}

Class members in Kotlin

A Class in Kotlin can have following members:

  • Primary constructor
  • Secondary constructor
  • Initializer blocks
  • Functions
  • Properties
  • Nested and Inner classes
  • Open declarations

Let’s take an example of a Vehicle class.

Like any other OOP language Classes in Kotlin can have properties like the number of doors, engine type, mileage covered and member functions.

Kotlin does not have fields in Classes.

Classes in Kotlin only allows properties.

How to define a class in Kotlin

class Vehicle {
     // properties or members of Vehicle class in Kotlin
     var doors: Int = 4
     var engineType: Int = 1
     var mileage: Int = 500

     // member functions of class   
     fun stopCar() {
        // stop car implementation goes here...
     }

     fun startCar() {
        // start car implemntation goes here...
     }
 }

In above code example, we used class keyword to declare a class in Kotlin.

  • And our class has three properties declared inside its body.
  • And it has two member functions declared in the body of a class.
  • Properties in Class are declared using keyword “var” as mutable data type.
  • And Member Functions are declared using “fun” keyword.

As you might have noticed that I have initialized properties of our Vehicle class in above code example.

 var doors: Int = 4  
 var engineType: Int = 1      
 var mileage: Int = 500

If we do not initialize properties like above, the compiler will give us an error message.

Properties in class must be initialized or declared abstract.

Creating an instance/Object of a class in Kotlin

To access properties and member functions of a class, we need an object of a Class.

An object contains all the information for a Class.

Note:-

No memory is allocated when you define a Class.

Memory is allocated only when you initialize an object of a class in Kotlin.

 

> Also there is no new keyword in Kotlin.

> You just have to write name of the class to initialize instance of class in Kotlin.

This is how we initialize a class and access its properties and member functions.

fun main(args: Array<String>) {

    // vehicle1 is an Object of our Vehicle class.
     var vehichle1 = Vehicle()
     vehichle1.engineType = 100
     vehichle1.startCar()
 
     var vehicle2 = Vehicle()
     vehicle2.engineType = 200
     vehicle2.startCar()
 }

We initialized Vehicle class by calling its default constructor as if it were a regular function.

We can access member functions and properties of Kotlin Classes, using dot (.) notation in Kotlin.

Let say I don’t want to initialize class properties like above.

I want to initialize those values when creating an object of a class.

As each object will have its own properties so their values should be initialized while creating an object of a class.

Now we will add a constructor to our  Vehicle class.

class Vehicle (initDoors: Int, initEngineType: Int, initMileage: Int){ 

     
  // properties or members of Vehicle class in Kotlin   
   var doors:Int  = initDoors
   var engineType:Int = initEngineType   
   var mileage: Int = initMileage    

  // member functions of class      

   fun stopCar() {        
      // stop car implementation goes here...   
   }   


   fun startCar() {     
    // start car implemntation goes here...
   } 
 }

Now we will initialize class properties through constructor while creating an instance of a class.

This is how we initialize a class and access its properties and member functions.

fun main(args: Array<String>) {

    // vehicle1 is an Object of our Vehicle class.
    // passing properties values while creating object of a class.

     var vehichle1 = Vehicle(4, 1, 100)
 
 }

Now class properties are not initialized by default instead, properties will be initialized when we will create an instance of a class.

I recommend you go through Data classes in Kotlin.

Interfaces in Kotlin

An interface is similar to Class but it is used to specify behavior a Class must implement.

Interface allows code reusability.

An interface in Kotlin can contain declaration of abstract method and method implementation.

How to define an Interface in Kotlin

interface IExample1 {
 
     // abstract method
     fun doSomething()
 
     // method with implementation
     fun doSomethingElse() {
     }
 
     var prop: String  // abstract property
     val properyWithImplementation :String
     get() = "interface propery with implementation"
 }

In above code example interface IExample1 is defined and it has

Two properties (one abstract and one with its own implementation)

Two methods (one abstract and one with its own implementation)

Kotlin Interface example

 interface IExample1 {
 
     // abstract method
     fun doSomething()
 
     // method with implementation
     fun doSomethingElse() {
         println("hello kotlin interface example")
     }
 
     var prop: String  // abstract property
 
     val properyWithImplementation :String
     get() = "interface propery with implementation"
 }

 class Child : IExample1 {
 
     override fun doSomething() {
         println("abstract method implemented by class implementing interface")
     }
 
     override var prop: String
         get() = "abstract property overrided by accessor here"
         set(value) {}
 }

fun main(args: Array<String>) {
 
     var child = Child()
 
     println(child.properyWithImplementation)
 
     child.doSomethingElse()
 
     child.doSomething()
 
     println(child.prop)
     
 }

The output of the above program will be

interface propery with implementation

hello kotlin interface example

abstract method implemented by class implementing interface

abstract property overrided by accessor here

Open, final and abstract modifiers in Kotlin

In java if we want to declare a class which cannot be inherited by any other class we mark it as Final using “final” keyword. By default all classes can be inherited in Java.

But in Kotlin by default all classes are final (cannot be inherited by default).

 class Base {
 }

 class Derived : Base() {
 }

If you write above code you will get compile time error “This type is final, so it cannot be inherited”.

If we want to specify a Class which can be inherited we use “open” keyword.

Open modifier Kotlin example

 open class Base {
 }
 
 class Derived : Base() {
 }

Now you will not get this type is final error.

Inheritance in Kotlin using “open” modifier example

fun main(args: Array<String>) {
 
     var derived = Derived()
     derived.addTwoNumbers()
     
 }
 open class Base {
     open fun addTwoNumbers() {
         println("base class function")
     }
 }
 class Derived : Base() {
     override fun addTwoNumbers() {
         super.addTwoNumbers()
         println("derived class function")
     }
 }

If you run the above program it will print following output:

base class function

derived class function

Abstract class in Kotlin example

Classes in Kotlin can be declared abstract similar to Java using “abstract” keyword.

If you want derived class to provide its own method implementation you can declare Class as abstract and mark its member function as abstract.

An abstract class cannot be initialized similar to Java.

An abstract member function does not provide its own implementation instead Class which derived from abstract Class override abstract method and provides implementation.

Kotlin abstract class and abstract member code example

fun main(args: Array<String>) {
     
     var secondDerived = SecondDerived()
     secondDerived.addTwoNumbers()
 }
 
 abstract class Derived {
     abstract fun addTwoNumbers()
 }
 
 class SecondDerived : Derived() {
     override fun addTwoNumbers() {
         println("this class will provide its own method implementation")
     }
 }

If you run this program you will get output:

this class will provide its own method implementation.

Recommended Reading:-

Kotlin Programming language idioms Tutorial with code examples

How to Develop Android Image Gallery App using Kotlin – Tutorial with Complete Source Code

Contact Us