Kotlin, Zero to Kotlin Hero

Zero to Kotlin Hero: Classes in Kotlin

In my previous article, I wrote about variables in the Zero to Kotlin Hero series.

In this article, we would cover classes and how to create objects in Kotlin.

 

What is an Object?

An object is an instance of a class. An object has states and behaviours. Example: a car has states – color, brand as well as behaviours – driving, reversing, parking.

 

What is a Class?

A class is a blueprint that defines attributes and behaviours that you use to create objects. A class is declared using the class keyword.

class Car{  //class header
   //class body
}

 

Class members

A class can contain constructors, functions, properties, nested classes and inner classes.

Constructors

A Kotlin class can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header: it goes after the class name (and optional type parameters).

class Car(brand: String){}

The init keyword is used to define an initializer block. This block contains initialization codes that are part of the primary constructor.

A class can also have one or more secondary constructors which are prefixed with the constructor keyword.

class Car(brand: String){             //primary constructor in class header
    init{                             //initializer block
       print("The car brand is $brand")
    }

    constructor(color: String, brand: String) : this(brand){    //secondary constructor
       print("In the secondary constructor of a $color $brand car")
    }

}

Objects are created like this:

val myCar = Car("Toyota")    //No new keyword

If an object is created using the secondary constructor and an init block exists in the class, the code of the init block will be executed first BEFORE the code in the secondary constructor. So looking at the code snippet above, if we declare an object with the Car("Toyota", "blue"), the line “The card brand is Toyota” is printed first before “In the secondary constructor of a blue Toyota car” gets printed.

 

Functions

Functions in Kotlin are declared with the fun keyword. If we were to create a function to paint our car, we can by doing something similar to what I have below:

fun paintOurCar(color: String){
   print("Our car is now $color")
}

 

Calling a function:

If a function is another class is accessible to you, it can be called by creating an object of the class first and “referencing” the function:

val myCar = Car("Toyota") 
myCar.paintOurCar("red")

However, if we are calling the function from the same class, we can simply do

paintOurCar("red")

The output of this function is Our car is now red.

 

Properties

Kotlin classes can have properties.

class Car {
    var name: String = "Adora's car"
    var brand: String = "Toyota Camry"
    var color: String = "red"
    var year: Int = 2018
}

They can be accessed like this:

val mycar = Car()   //creating the object

var carname = mycar.name      //getting the car name
var carbrand = mycar.brand    //getting the car brand
var carcolor = mycar.color    //getting the car color
var caryear = mycar.year      //getting the car year


 

Nested classes

When a class is created in another class, then it is a nested class. In Kotlin, a nested class is static by default. Due to this, you do not have to create an instance of that class to access its members.  A nested class is illustrated below:

class Car{
    class NestedCar{
        fun welcome(){
           print("Welcome to the Nested Car class")
        }
    }
}

To call the function welcome() in this NestedCar class, we have to gain access to the NestedCar class first like the function below:

Car.NestedCar().welcome()

This would print "Welcome to the Nested Car class".

 

Inner classes

A nested class may be marked as inner to be able to access members of the outer class. With normal nested classes, access to members of the outer class is prohibited. Inner classes carry a reference to an object of an outer class:

class Car {
    private val welcomeMsg: String = "You are welcome"
  
    inner class AnotherNestedCar {
      fun welcome(){ print(welcomeMsg) }
    }
}

Car().AnotherNestedCar().welcome() // == You are welcome

 

Inheritance

Inheritance is a mechanism where you can derive a class from another class for a hierarchy of classes that share some attributes and methods. The class being derived from is usually the super class (or base class).

In Kotlin, the base class is called Any. The syntax for inheritance in Kotlin is:

class Tesla : Car{

}

In this example, Tesla is inheriting some properties from the super class Car.

The override keyword:

There are instances where the base class has a property that you want to redefine (maybe because you want to add to it) in your own class as well. In times like this, the override keyword is used to make the play() class in the subclass the called class. See below:

open class FirstClass {
   open fun play () {
      print("Yay. Let's play chess.")
   }
}
class SecondClass: FirstClass() { 
   override fun play() {
      print("Chess is boring. Let's play checkers")
   }
}
fun main() {
   var sampleObject = SecondClass()
   sampleObject.play()
}

With the override keyword, the output for this code snippet would be: Chess is boring. Let’s play checkers.

Without the override keyword, the code would actually not execute so you may have to change the function name or override the function having the same name in the base class.

 

Conclusion

We have seen some of the basics of Object Oriented Programming in Kotlin. If you want to see more examples on Kotlin Classes and OOP Concepts, please go to my GitHub. Get ready to know about Kotlin access modifiers in the next article!

 

Spread the love

Leave a Reply

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