Learn Kotlin with me: Classes and Objects

Hitesh Kohli
3 min readJun 8, 2024

--

Photo by Patrick on Unsplash

Classes and Objects is one of the most basic and important topics in Software engineering. I am sure that you are familiar with them. In this blog post, I will try to break down classes and objects with Kotlin.

Welcome to the “Learn Kotlin with me” series, in this series of blog posts and videos, I will try to break down Kotlin and distribute it to you guys. If you guys want to watch this in the form of a video. Here is the link:

Classes and Objects:

Let me ask you a quick question. How do you make a real-world entity like a car in a software world? Is it even possible to do it?

Let’s try to understand this with an example. A car is a real-world entity which has an engine, tyres and breaks. In the software world, this real-world entity should work like it does in the real world. What is the closest thing that can help us translate its engine starting or braking systems?

It is possible to depict it using functions or methods. For example, an engine start method would start the engine, or a break function might activate breaks.

Also, we can use variables to show its properties. Like the engine, number of tyres or breaks.

What if we wanted to make a blue-print? So that we can translate every vehicle from the real world to the software world. How can we do so?

Here comes the need for classes. Classes are the blueprints we use to translate real-world entities. Objects are real-world entities translated into the software world.

Let’s try to make one and keep on exploring its properties

Here is an example of a simple vehicle class:

Let’s try to make an object from this class:

Let’s try to modify the properties of an object:

As you can see, the bracket in front of the class is a constructor. There are two types of constructors:

  • Primary Constructor
  • Secondary Constructor

The primary constructor is used to enter values inside the object. The secondary constructor is used to pass default values inside the class. Let’s try to understand this with an example:

Another important concept is called “init”. This function calls itself as soon as the class is declared. Let’s try to understand with an example:

I hope this makes classes and objects a little clearer. Thank you for reading this blog. If I have written something wrong please forgive me and correct me in the comments.

Thank you for your most precious thing, your time

Your Captain (the commute)

Hitesh Kohli

--

--

Hitesh Kohli

Hi, my name is Hitesh Kohli, I work at Geeks for Geeks as an Android developer. I love messing around with apps and games.