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.

In this article we will cover

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

Classes and Objects in Kotlin

Let us first understand what are Classes and Objects.

Class is a user defined data type which can have properties and member functions inside body of a Class.

For example a Vehicle class.

Classes in Kotlin can have properties like number of doors, engine type, mileage and member functions.

How to define a class in Kotlin

class Vehicle {
     // properties of Vehicle class
     var doors: Int = 0
     var engineType: Int = 0
     var mileage: Int = 0

     // member functions    
     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 body of a Class.  And it has two member functions.

Properties in Class are declared using keyword “var” as mutable data type.

And member functions are declared using “fun” keyword.

Properties in class must be initialized or declared abstract.

Creating an instance of a Class in Kotlin

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

An object contains all the information for a Class.

Note: no memory is allocated when you define a Class.

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

fun main(args: Array<String>) {

     var vehichle1 = Vehicle()
     vehichle1.engineType = 100
     vehichle1.startCar()
 
     var vehicle2 = Vehicle()
     vehicle2.engineType = 200
     vehicle2.startCar()
 }

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

We can access its member functions and properties, using dot (.) notation.

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

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 language idioms introductory tutorial part-1

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

2 thoughts on “Classes, Objects, Modifiers and Interfaces in Kotlin Tutorial”

Leave a Reply

Your email address will not be published. Required fields are marked *