image
Constructors - Part 2
Start course
Difficulty
Intermediate
Duration
1h 31m
Students
44
Ratings
5/5
Description

This course covers the concept of Object-Oriented Programming in Kotlin, which is a method of designing and implementing software. It simplifies software development and maintenance by providing concepts such as object, class, inheritance, polymorphism, abstraction, and encapsulation. This course will explore those.

Intended Audience

This course is ideal for anyone who wants to learn how to use Kotlin for developing applications on Android.

Prerequisites

This content will take you from a beginner to a proficient user of Kotlin and so no prior experience with the programming language is required. It would, however, be beneficial to have some development experience in general.

Resources

Course GitHub repo: https://github.com/OakAcademy/Kotlin-Programming-Course/tree/main/ObjectOrientedProgramming

Transcript

All right. Hello, friends. So, in our previous lesson, we talked about constructor, theoretically, but we also learned how to create classes and objects in Kotlin, practically. So, that means in this lesson we're going to do a little practice with constructor. All right, so let's get to it. Hopefully, remember we created a Kotlin class called Cars in our previous lesson. Now, this Kotlin class also had two properties: name and model. We also created two objects of the Cars class in the main method. Great, and then using these objects, we passed some values to the name and the model variables. Now, did you notice, we first created an object and then passed a value using the object. So, what do you think we ought to do if we wanted to use it to transfer these values while creating an object from any class? So, this, you understand what I'm saying? Well, I'll tell you. Because we're going to make a constructor. The constructor was the first method called when creating an object from a class. So, why don't we do this? Let's create a new class right now, and we'll try to understand the constructor just a little bit better using this class. All right so, first, just right-click on the project package folder, choose 'New' 'Kotlin Class/File' option. Now, here the class is going to be selected. So, why don't we call this class MyCars, create the Kotlin class, just by pressing 'Enter'. Now, do you remember when we talked about the constructor? In the previous lesson, we talked about two different constructors structures in Kotlin, and these were primary and secondary. So, we'll have a look at the primary constructor first. To create a primary constructor, we'll write the constructor expression after the class name. When we start to write the constructor, the code editor proposes that constructor to us. Select it, press 'Enter'. Now, write their name in the model variables in parenthesis. Cool, so here I am writing var name: String, and after putting in a comma we can define the model variable. So, I'll type var model :Int. All right, so here we've created the primary constructor. Now, let's create an object of this class in the main method. We'll turn the codes that we wrote in the previous lesson into a comment line. That's right, creating an object from class here. That way you'll be able to understand these codes a little bit more easily when you go back and review them. All right, so let's create an object from the myCars class. And here I am typing var_myNewCar = MyCars(). And see how Android Studio gives a warning, because we need to enter a name and model parameters in parenthesis? Because we wanted the name and model parameters to be entered in the constructor. At this point, hopefully you understand the purpose of the constructor. You see, if we did not use the constructor, we could create objects without entering these parameters.

However, sometimes we may want to enter some parameters while creating objects with the projects that we develop, you follow? So, in this case it is best to use a constructor. All right. So, without any further ado, let's enter some parameters. All right, Ferrari is the first parameter, 2021 is the second parameter. Now, let's print these values to the console. I'll type sout and press 'Enter', I'll write, My car's name is ${myNewCar.name} and its model is ${myNewCar.model} in parenthesis. Now, let's run our code. All right. So, as you can see, we've printed the name and the model of the car on the console. Okay, so that's how you use the primary constructor. Now, I want to show you something, how to use the init keyword. So, in Kotlin, you wouldn't be able to directly write a block of code inside the primary constructor. If you want to write some code, you should be doing so using the init keyword. So, I'll give you an example, let's try to print the name of the model of the car to the console. Not in the main method, but in the constructor of the MyCars class. All right, so, I'll first convert this line of code into a comment line. So, now let's go back to the class. I'll write sout here, but as you can see, we cannot write sout. More precisely, we encountered this error when trying to write it. Okay, so this is because no code can be written directly into the primary constructor. So, for this we need to use the keyword init. So, after typing init here, I'll select the 'init' expression suggested by the code editor and press 'Enter'. What happens next, a block has formed for us. So, now let's try to write sout inside this init block. And as you can see, we don't encounter any more errors. So, I create the printIn method by pressing 'Enter'. In parenthesis, I'll write My car's name is $name and its model is $model. Let's run our code again. And here you can see we were able to see the name of the model of the car on the console screen. So, my friends, that is using the primary constructor in Kotlin. Now, let's have a look at the secondary constructor.

All right, because we've built it up pretty big here. I already told you that the secondary constructor is similar to the constructor in Java. That means you can create multiple constructors using the secondary constructor. Of course, if there are any friends out there who know Java programming, we could create empty and full constructors in Java. You can create empty and full constructors just by using the secondary constructor in Kotlin as well. So, let's do that right now. First off, we'll create a new class. So, in fact, we can explain all of these concepts through the same class. But since I do want to share these codes with you, I just want to examine them a little more easily. So, for that reason I'm just going to explain it in separate classes as much as is possible. So, here we can just put the name of this class to be MySecondCars. So, now let's create two variables for this class. So, here I can type var name: String? = null. Just below the line, I'm typing var model:Int? = null. Now, let's create the secondary constructor. There are actually two different ways to create it. The first is manually, the second one is using a shortcut in the code editor. So, I want to show you how to do it manually first because then you'll understand what the shortcut does. So, when I write the constructor here, I'll select the constructor suggested by the code editor and press 'Enter'. Now, if you leave it that way, it is expressed as an empty constructor, but we will create a full constructor. That is a constructor that includes both variables. So, for this, I'll write the name: String in paranthesis and I'll write the model:Int after the comma. Now, I'll open curly braces and specify the scope of this constructor. Here, using the this keyword, we will pass the name and model information that will come from the main method with the help of the constructor to the name and model variables that we have created here. All right, so let's do this right now. So, I'm just typing this.name = name here. And this is the first time that you see this type of writing. So, let's try to explain a little bit. The this keyword represents a class to which the method is bound. So, here it represents the MySecondCars class. So, the name that comes after this statement represents a variable named name that we created in the class. The name that we write to the right of the = sign represents a value that we will specify in the main method with the help of the constructor, and will be transferred to the variable named name. You could also write a different expression instead of name here. For example, you can write n instead of name. It's not going to cause any errors, but the secondary constructor is generally adaptable in this way. So, similarly, now I can write this.model = model. So, we created the secondary constructor like that. So why don't we do this?

Let's create the secondary constructor using the shortcut and the code editor. So, let me just delete the constructor here. All right, right click on the empty space, choose the 'Generate' and 'Secondary Constructor' options from the popup menu. So, if you notice, we can see the variables named name and model in this window. And if you press the 'Select None' button without selecting these variables, you will get an empty constructor. But right now I want to right click and select the 'Generate' and 'Secondary Constructor' options. That would be an interesting new word. Anyway, this time I want to choose both variants. So, you can select both variables just by pressing the 'Ctrl'  key on the keyboard.

So, I'll create the secondary constructor by clicking the 'OK' button. And as you can see, the secondary constructor is created automatically, just like that. Of course, you could use either one of these two methods however and whenever you want. But now I want to create an object of this class in the main method. So here, I will write var_mySecondCar = MySecondCars(). Now notice that although we create the constructor, we did not get an error, even if we don't write any parameters in the parenthesis. Can you tell me why? Well, I'll tell you. It's because we are creating an empty constructor. So, why don't we do this? Let's turn the empty constructor in the class MySecondCar into a comment line. Now, if we look at the main method, as you can see, we are now getting an error. Because there's only a full constructor and we need to enter parameters here. So, what do I do? I'll write Mercedes as the first parameter. I'll type in 2000 as a second parameter.

Now, let's print this to the console. So, I'm copying the line of code here and pasting it here. I'll type in second here and also arrange these objects as mySecondCar. Now we can run our code. As you can see, we have printed the name and model of the car on the console. Yes, friends, this is how to use the primary and secondary constructors in Kotlin. I hope it has been a useful lesson for you. Before I end the lesson, I want to show you one more thing. Notice that we have set the value of the variables named name and model during object creation. This was because we created the constructor. Well, can we change the values we assign to the objects named name and model? In other words, is it possible to change the values we assign while creating an object later? Let's explain this situation with a simple example. Currently, the value of the variable name is Mercedes, and the value of the model variable is 2000. Now let's change these values. Here I write mySecondCar.name =. This time, let's name the car Opel. Similarly, let's pass a value to the model variable. I'm writing mySecondCar.model =. Let's transfer the value of 2010 to the model variable. So, when we run the code, do you think we will see the new values or the old values on the console screen? Any ideas? Let's run the code and see together. And as you can see, we saw the new values, namely Opel and 2010 values on the console screen. This is because the set method is automatically created in the Kotlin programming language. If you want, let's end this lesson here. And in the next lesson, let's focus on set and get methods and encapsulation. See you in the next lesson.

 

About the Author

Mehmet graduated from the Electrical & Electronics Engineering Department of the Turkish Military Academy in 2014 and then worked in the Turkish Armed Forces for four years. Later, he decided to become an instructor to share what he knew about programming with his students. He’s currently an Android instructor, is married, and has a daughter.

Covered Topics