Object and Class in Kotlin With Example

This is 1st post of OOPS series in Kotlin. Here, we will talk about class in Kotlin. We will see what is it and why do we need it, a detailed explanation on how can we use it etc.

In computer world, we try to imitate real life scenarios. We try to create digital world same as what we see in real life. In order to do so, we have developed OOP concepts – class, interface, inheritance etc. A concept that provides facility to describe features of anything similar as what we see in real life. Don’t bother about technical words – class, interface, inheritance etc. . We will learn about each term one by one.

For example,
Many of us have seen a Dog. Here is how they look –
Tutorialwing Kotlin Class and Objects Examples of class in kotlin

We have a variety of Dogs in image –

  • Dog 1 is white, while Dog 2 is black in color. Moreover, Dog 2 does not have a tail.
  • Dog 3 is running while Dog 4 is actually a puppy.
  • Dog 5 is multi-color while Dog 6 is actually a Wooden Dog ( i.e. a toy)
  • Dog 6 can neither bark nor run.

What if we want to create such Dogs in digital world? How can we create them?

Here comes concept of Class!

Class in Kotlin

Did you look at different Dogs shown above? What can be their’s features ?

It can be –

  • Height of Dog?
  • Weight of Dog?
  • Colour of Dog?
  • Can it Swim?
  • Can it Run?
  • Can it Bark?
  • Does it have tail?
  • and many others

We can categories above features in two groups –

  • State – colour, weight, height of the Dogs. In other words, it can be values of physical appearance.
  • Behaviour – This includes operations or things that Dog can perform. for example, Can it Run?, Can it Bark?, Does it have tail? etc.

Any Dog have some states and behaviours. So, this is how we represent any Dog.

DOG_CLASS {
 // states
 // behaviours
}

In Kotlin, every class has some states and behaviours.

Now, our task is to design a class in Kotlin that describes above features of Dog.

Create a Class

We can create a class in Kotlin using class keyword. For example,

  class Dog {
  }
 

Here, we created a class named Dog.
Since this class has no body, we can omit curly braces and write it as –

  class Dog
 

Class name should use UpperCamelCase

As of now, our class is empty. It means we have defined a class Dog that does not contain any property.
Now, we will add it’s property one by one –

class Dog {
 var weight: Double = 0.0
}

We added property weight. It’s value will decide how heavy Dog is.

Similarly, we can add another property – If it can swim or not.

class Dog {
 var weight: Double = 0.0
 fun swim() {
 // Write how does it swim etc...or if it's really swim or not.
 }
}

Method swim() explains the ability of Dog if it swims or not.

Similarly, we can define other features of Dog.

class Dog {
 var weight: Double = 0.0
 var height: Double = 0.0
 var color: Double = 0.0

 fun swim() {
  // Write how does it swim etc...or if it's really swim or not.
 }

 fun run() {
  // Write how does it run etc...or if it's really run or not.
 }

}

But, we have a problem!

Till now, we have only defined how does a Dog Behave, it’s ability etc.
There is no real object… Dog!. You can just say a Dog have defined states and behaviours. But, where is the Dog?

OK!
So, how do we get a real Dog?

We can clearly see that a class contains only blueprint of the thing.
It’s like writing all the features of a cat in notepad. It defines cat. But, it’s not real cat.
Same is the case with Class. It just describes about that thing.

So,

What do you need to do?

You need to define an instance of the class.

OK!

So, how do we create instance of the class in Kotlin ?

To define instance in Kotlin, we use constructor.

Constructor in Kotlin (Create an Object)

To create an object (or instance) of the class, we call constructor as if it were a regular function.

 val dog = Dog()

Note that we have called Dog(). Here,
Dog is class name.

val dog = Dog() means we have created an object of the class Dog. That means we have a real object (i.e. Dog) now.

When you call a class name as function, it actually calls constructor of that class.

Similarly, you can define many instances of the class. For example,

 val dog1 = Dog()
 val dog2 = Dog()
 val dog3 = Dog()
 val dog4 = Dog()

We have created 4 instances of Dog. It means we have 4 Dog that have similar properties. Note that we have not set any value to any object. So, it will have default values.

Kotlin Class Example

Look at above image carefully, let’s create a class and object to represent them.
Here is how we do it –

class Dog {
 var weight: Double = 0.0
 var height: Double = 1.0
 var color: String = ""

 fun swim(): Boolean {
   return true
 }

 fun bark(): Boolean {
  return true
 }

 fun running(): Boolean {
  return false
 }

}

fun main() {
 val dog1 = Dog()
 dog1.color = "White"
 dog1.weight = 13.0

 println("Dog 1: height - ${dog1.height} , " +
         "bark - ${dog1.bark()} , " +
         "weight (in kg.) - ${dog1.weight} , " +
         "swim - ${dog1.swim()} , " +
         "running - ${dog1.running()} , " +
         "color - ${dog1.color}"
 )

 val dog2 = Dog()
 dog2.color = "Black"
 dog2.weight = 23.0

 println("Dog 2: height - ${dog2.height} , " +
         "bark - ${dog1.bark()} , " +
         "weight (in kg.) - ${dog2.weight} , " +
         "swim - ${dog2.swim()} , " +
         "running - ${dog2.running()} , " +
         "color - ${dog2.color}"
 )

 val dog3 = Dog()
 dog3.color = "Brown"
 dog3.weight = 19.0

 println("Dog 3: height - ${dog3.height} , " +
         "bark - ${dog1.bark()} , " +
         "weight (in kg.) - ${dog3.weight} , " +
         "swim - ${dog3.swim()} , " +
         "running - ${dog3.running()} , " +
         "color - ${dog3.color}"
 )

 val dog4 = Dog()
 dog4.color = "White"
 dog4.weight = 3.0

 println("Dog 4: height - ${dog4.height} , " +
         "bark - ${dog1.bark()} , " +
         "weight (in kg.) - ${dog4.weight} , " +
         "swim - ${dog4.swim()} , " +
         "running - ${dog4.running()} , " +
         "color - ${dog4.color}"
 )

 val dog5 = Dog()
 dog5.color = "Multi Color"
 dog5.weight = 23.0

 println("Dog 5: height - ${dog5.height} , " +
         "bark - ${dog1.bark()} , " +
         "weight (in kg.) - ${dog5.weight} , " +
         "swim - ${dog5.swim()} , " +
         "running - ${dog5.running()} , " +
         "color - ${dog5.color}"
 )

 val dog6 = Dog()
 dog6.color = "Red"
 dog6.weight = 2.0

 println("Dog 6: height - ${dog6.height} , " +
         "bark - ${dog1.bark()} , " +
         "weight (in kg.) - ${dog6.weight} , " +
         "swim - ${dog6.swim()} , " +
         "running - ${dog6.running()} , " +
         "color - ${dog6.color}"
 )

}

Run the program, we will get output as below –

Dog 1: height - 1.0 , bark - true , weight (in kg.) - 13.0 , swim - true , running - false , color - White
Dog 2: height - 1.0 , bark - true , weight (in kg.) - 23.0 , swim - true , running - false , color - Black
Dog 3: height - 1.0 , bark - true , weight (in kg.) - 19.0 , swim - true , running - false , color - Brown
Dog 4: height - 1.0 , bark - true , weight (in kg.) - 3.0 , swim - true , running - false , color - White
Dog 5: height - 1.0 , bark - true , weight (in kg.) - 23.0 , swim - true , running - false , color - Multi Color
Dog 6: height - 1.0 , bark - true , weight (in kg.) - 2.0 , swim - true , running - false , color - Red

You can check how to take input and print output in kotlin in detail.

Here, we created 6 objects of Dog class. We have set each object’s –

  • weight
  • color

Note that we have not set below things for any object –

  • height to any object.
  • Does it swim?
  • Is it running?
  • Does it bark?

So, it has default values whatever we set while defining Dog. This is what we should do. If we know some values to be same for every instance of the Class, we should write these in Class itself.

But, there is another problem!

All Dog objects we created bark and swim. Moreover, all of them are running. Everyone has height of 1.0 metre. But, Is it so?

Look at the image carefully!

Dog 6 can neither bark nor run. But, we defined that Dog 6 is running and can also bark.
Moreover, only Dog 3 is running. But, we defined that All Dogs are running.

Got the problem ?

how do we solve it?

Answer to this question is – Inheritance

We can use inheritance properties of OOP concepts to do above task.

In upcoming post, we will be discussing about inheritance. We will see merits/demerits of inheritance and how we can use interface to solve such problems of inheritance.

Summary

  • A class is basic building block in object-oriented programming languages that defines a set of properties and methods that are common to all objects of one type.

    Could n’t understand a single word. Can you please make it easier?

    In other words,
    A kotlin class is blueprint/template for creating objects of similar types that contains –

    • state – It tells us about type or value of an object. For example, states of Dog can be weight, colour, height etc. It is represented using variables.
    • behaviour – It tells us about operations or things that object can perform. For example, Dog can swim, run, bark etc. It is represented using functions.
  • An object is an instance of the class that have behaviours and states represented by class.

Leave a Reply