Kotlin tutorial for Beginners – Kotlin Class and Objects

Kotlin Class and Objects

In this article, you’ll be introduced to Object-oriented programming in Kotlin. You’ll learn what a class is, how to create objects and use it in your program.

Kotlin supports both functional and object-oriented programming.

Kotlin supports features such as higher-order functionsfunction types and lambdas which makes it a great choice for working in functional programming style. You will learn about these concept in later chapters. This article will focus on object-oriented style of programming in Kotlin.


Object-oriented Programming (OOP)

In object-oriented style of programming, you can divide a complex problem into smaller sets by creating objects.

These objects share two characteristics:

  • state
  • behavior

Let’s take few examples:

  1. Lamp is an object
    • It can be in on or off state.
    • You can turn on and turn off lamp (behavior).
  2. Bicycle is an object
    • It has current geartwo wheelsnumber of gear etc. states.
    • It has brakingacceleratingchanging gears etc. behavior.

You will learn about detail features of an object-oriented programming like: data encapsulationinheritance and polymorphism as we go on. This article will focus on the basics to keep things simple.

 


Kotlin Class

Before you create objects in Kotlin, you need to define a class.

A class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.

Since, many houses can be made from the same description, we can create many objects from a class.


How to define a class in Kotlin?

To define a class in Kotlin, class keyword is used:

class ClassName {
    // property
    // member function
    ... .. ...
}

Here’s an example:

class Lamp {

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }
}

Here, we defined a class named Lamp.

The class has one property isOn (defined in same way as variable), and two member functions turnOn() and turnOff().

 

In Kotlin, either the property must be initialized or must be declared abstract (Visit: Kotlin Abstract Class to learn more). In the above example, isOn property is initialized to false.


Classes, objects, properties, member function etc. can have visibility modifiers. For example, the isOn property is private. This means, the isOn property can be changed from only inside the Lamp class.

Other visibility modifiers are:

  • private – visible (can be accessed) from inside the class only.
  • public – visible everywhere.
  • protected – visible to the class and its subclass.
  • internal – any client inside the module can access them.

 

If you do not specify the visibility modifier, it will be public by default.

In the above program, turnOn() and turnOff() member functions are public whereas, isOn property is private.


Kotlin Objects

When class is defined, only the specification for the object is defined; no memory or storage is allocated.

To access members defined within the class, you need to create objects. Let’s create objects of Lamp class.

class Lamp{

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }
}

fun main(args: Array<String>) {

    val l1 = Lamp() // create l1 object of Lamp class
    val l2 = Lamp() // create l2 object of Lamp class
}

This program creates two objects l1 and l2 of class Lamp. The isOn property for both lamps l1 and l2 will be false.


How to access members?

You can access properties and member functions of a class by using . notation. For example,

l1.turnOn()

This statement calls turnOn() function for l1 object.

Let’s take another example:

l2.isOn = true

Here, we tried to assign true to isOn property of l2 object. Note that, isOn property is private, and if you try to access isOn from outside the class, an exception is thrown.


Example: Kotlin Class and Object

class Lamp{

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }

    fun displayLightStatus(lamp: String) {
        if (isOn == true)
            println("$lamp lamp is on.")
        else
            println("$lamp lamp is off.")
    }
}

fun main(args: Array<String>) {

    val l1 = Lamp() // create l1 object of Lamp class
    val l2 = Lamp() // create l2 object of Lamp class

    l1.turnOn()
    l2.turnOff()

    l1.displayLightStatus("l1")
    l2.displayLightStatus("l2")
}

When you run the program, the output will be:

l1 Lamp is on.
l2 Lamp is off.

In the above program,

  • Lamp class is created.
  • The class has a property isOn and three member functions turnOn()turnOff() and displayLightStatus().
  • Two objects l1 and l2 of Lamp class are created in the main() function.
  • Here, turnOn() function is called using l1 object: l1.turnOn(). This method sets isOn instance variable of l1 object to true.
  • And, turnOff() function is called using l2 object: l1.turnOff(). This method sets isOff instance variable of l2 object to false.
  • Then, displayLightStatus() function is called for l1 and l2 objects which prints appropriate message depending on whether isOn property is true or false.

Notice that, the isOn property is initialized to false inside the class. When an object of the class is created, isOn property for the object is initialized to false automatically. So, it’s not necessary for l2 object to call turnOff() to set isOn property to false.

For example:

class Lamp{

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }

    fun displayLightStatus() {
        if (isOn == true)
            println("lamp is on.")
        else
            println("lamp is off.")
    }
}

fun main(args: Array<String>) {

    val lamp = Lamp()
    lamp.displayLightStatus()
}

When you run the program, the output will be:

lamp is off.

This article is just an introduction to object-oriented programming in Kotlin. Check these chapters in sequence to learn more:

  • Kotlin Constructors and Initializers
  • Kotlin this Keyword
  • Kotlin Nested Class

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.