In this section, we will learn what the Class and Objects are and how to use them in Kotlin.
What is Object Oriented Programming in Kotlin?
Kotlin is an object-oriented programming language! That means every single value you see in this language is an object on its own!
We call values as objects for two reasons:
- In the real world, objects have properties! Properties are the information that an object knows about itself. For example, objects might have color, weight, shape. These are the properties of an object in the real world. Now, in Kotlin, values (AKA objects) have properties as well! For example, consider a String value; a String value is an object because it has properties like length (which declares the number of characters it has).
- In the real world, objects have functions that we can use to do things with those objects! For example, consider a Car; It is an object with functions! For example, it has gas pedal which we used to increase or decrease the speed of the car (Speed here is the property of that car), it has steering wheel by which we can change the direction of the car and other types of functions that you can see in a car. Now, on the same page, values in Kotlin have functions as well! For example, a String value has a function that allows you to change the entire characters of the target value into uppercase or lowercase. It has functions that allow you to convert a String value into other data types, etc.
So because values in Kotlin have the same features as those in real worlds, we say values in Kotlin are objects.
What is Class in Kotlin?
So far, every object we’ve seen in the Kotlin was built-in. For example, a value (object) of type String, an Integer object, Float object etc. these are all built-in objects. This means the moment you put the value in a program, behind the scene, its object will be created and basically the properties and functions related to that value are preset. So you know in advance what properties and functions are available for each mentioned object.
But what if we want to create our own objects in Kotlin? What if we want to create an object named Car? How to do that?
Well, this is where the Class comes in!
Kotlin knows that it doesn’t have every object in the universe! So it supported those basic types (those that every developer might come across no-matter what type of program you’ll create) and then for the rest of objects that developers might need, provided a set of methods that they can use in order to create their own objects!
One of these methods is using Classes.
As mentioned before, an object has two things:
- Properties
- Functions
Now the question is how do we design an object to have x number of properties and y number of functions? How do we define an object to have a function that does a specific task?
Well, this is the job of classes!
In Kotlin, when we want to create an object, we first start by creating the blueprint and map of that object using classes.
Basically, a class is your area of design for a new object! You can set as many properties and functions there.
At the end we use a class to build up an object from.
Note: when creating a variable and store a value of built in type like String for example, Kotlin automatically and behind the scene uses a class called String
and creates an object that will hold your value inside of it. So throughout this tutorial and in the examples of previous sections, we’ve been creating objects, but we just didn’t know it at the time.
Alright, now let’s go and see how we can actually create a class in Kotlin.
How to declare a class in Kotlin? (Defining Classes in Kotlin)
class ClassName{ #the body of the class where we can set the properties and functions. }
class
: to create a class, we first start with the keyword class.
ClassName
: this is a name we set for a class and then use that name to invoke the target class and create an object from it.
{}
: within the body of the pair of braces that comes after the name of a class, we can set any number of properties and functions we want. These properties and functions will be then attached to the objects that we create from the class. So anything you put here will be part of the future objects of the class.
Example: creating a class in Kotlin
class Person{ lateinit var firstName: String lateinit var lastName: String fun setNameAndLastName(fName:String, lName:String){ firstName = fName lastName = lName } fun getNameAndLastName():String { return "The name is: ${firstName} and the last name is: ${lastName}" } }
Here the name of the class is Person
and as you can see, it has properties and functions.
Now let’s get into the details to see what properties and functions are in the body of a class.
Members of a Class in Kotlin:
The members of a class consist of properties and functions.
– Functions are exactly the same as the way we’ve been creating them so far but outside of a class. Here inside the class now we create functions and these functions will be part of the objects that we will create from the target class.
In the last example, we’ve set two functions for the Person class. The first one setNameAndLastName
is used to set the values for the properties of this class. The second getNameAndLastName
is used to return the current value of these properties.
So now if we create an object from the Person
class, it will have two mentioned functions and we can use the object to call them. (Which you’ll soon see how to do that).
– Properties, on the other hand, are nothing but local variables in a class! The way we create them in a class is exactly like the way they are created outside of a class, with one little exception:
By default, when creating a variable (property) in a class, it must be initialized with a value! For example, if the variable is of type String, then you should pass a string value to it. Otherwise you’ll get an error. But if you don’t know the value of the property until the runtime, then you can use the lateinit
keyword in front of the target property. This way we’re telling the Kotlin that we don’t know the value of the property, but we will initialize it at runtime.
For example:
lateinit var firstName: String lateinit var lastName: String
Here, these two properties are declared without any initialization, so we’ve used the lateinit
keyword in front of them.
Note that we’re talking about properties of a class and not local variables that could be created inside the function of a class! Those can be created without the use of lateinit keyword.
Alright, know that we know what a class is and saw its members, let’s go and see how we can create an object from a class then.
Kotlin What is Object?
An object is the built version of what we define in a class!
A class on its own is not useful in a program until we create an object from it!
So objects are the actual tools built from classes that we can practically use in our program.
How to Create Objects in Kotlin?
This is how we can create an object from a class:
var variable_name = ClassName()
ClassName()
: this is the name of the class we want to create an object from. We then put a pair of parentheses after the name of the class and so, as a result, a new object will be created from that class.
var variable_name
: the object we create from a class will be stored in a place called Heap Memory and only the address of that object will return and we can store it in a variable. So here the variable_name
basically represents the newly created object.
We can then use the variable_name
to access the members (properties and functions) of an object.
Note: the pair of parentheses that come after the name of a class is called constructor. We will talk about it in the Kotlin Constructors section.
Example: creating objects in Kotlin
class Person{ lateinit var firstName: String lateinit var lastName: String fun setNameAndLastName(fName:String, lName:String){ firstName = fName lastName = lName } fun getNameAndLastName():String { return "The name is: ${firstName} and the last name is: ${lastName}" } } fun main(){ var person = Person() }
Here we’ve created an object from the Person
class and assigned that to the person
variable.
So now we can use the person variable to access the members of this new object.
Alright, now let’s see how we can access the members of an object.
How to Access Members of an Object?
In order to access the members of an object, we use the dot operator as:
objectName.member_name
objectName
: this is the variable that represents the newly created object.
member_name
: This is the name of the member of that object (either property or function) that we want to invoke.
Example: accessing members of an object in Kotlin
class Person{ lateinit var firstName: String lateinit var lastName: String fun setNameAndLastName(fName:String, lName:String){ firstName = fName lastName = lName } fun getNameAndLastName():String { return "The name is: ${firstName} and the last name is: ${lastName}" } } fun main(){ var person = Person() person.setNameAndLastName("John","Doe") println(person.getNameAndLastName()) }
Output:
The name is: John and the last name is: Doe
So here we’ve used the person
variable which represents the newly created object from the Person
class and called two of its functions setNameAndLastName
and getNameAndLastName
.
In this example, we didn’t invoke the properties of the object, but if we wanted to do, it would be something like this:
person.firstName = value person.lastName = value
This is the statement of assigning a value to the properties.
And of course if we just wanted to get the values of the properties, we drop the assignment operator:
person.firstName person.lastName
Multiple Objects from a Class in Kotlin
When you have a class, there’s no limit on how many objects you can create from that class!
But the important thing to remember is that each object will have its own copy of the members of that class!
For example, if the class is set to have 2 properties and two functions, each object will take its own copy of these properties and functions and can set any values for the properties without affecting the other objects created from the same class.
Example: creating multiple objects from a class in Kotlin
class Person{ lateinit var firstName: String lateinit var lastName: String fun setNameAndLastName(fName:String, lName:String){ firstName = fName lastName = lName } fun getNameAndLastName():String { return "The name is: ${firstName} and the last name is: ${lastName}" } } fun main(){ var john = Person() var jack = Person() john.firstName = "John" john.lastName = "Doe" jack.firstName = "Jack" jack.lastName = "Bauer" println(john.getNameAndLastName()) println(jack.getNameAndLastName()) }
Output:
The name is: John and the last name is: Doe The name is: Jack and the last name is: Bauer
Here we’ve created two objects from the Person class and both objects have their own independent values for their variables.