Lesson 24 – Object-oriented programming concepts in kotlin Language

Lesson 24 – Object-oriented programming concepts in kotlin Language

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

Kotlin allows us to use the methodology of object-oriented programming.

Object-oriented programming (OOP) will introduce concepts of object, class, property, field, method, constructor, inheritance, and so on. And all these issues will be solved problems solved.

Virtually all languages developed in the last 25 years implement the possibility of working with Object-Oriented Programming (OOP)

Objects Basics

An object is an independent entity with its own data and programming. Windows, menus, file folders can be identified as objects; The motor of a car is also considered an object, in which case its data (fields and properties) describe its physical characteristics and its programming (methods) describe the internal functioning and its interrelation with other parts of the car (also objects).

The refreshing concept of the Orientation to Objects technology is the sum of functions to elements of data, to this union is called encapsulation. For example, an Auto object contains wheels, engine, speed, color, etc., called attributes. Encapsulated with this data are the methods to start, stop, bend, brake etc. The responsibility of an auto object is to take appropriate actions and keep your internal data up to date. When another part of the program (other objects) need the car to do any of these tasks (for example, start) it sends a message. These objects that send messages are not interested in the way in which the auto object carries out its tasks nor the data structures that it manages, therefore, they are hidden. Then, an object contains public information,

Class Concept and Object Definition

Object-oriented programming is based on class scheduling; Unlike structured programming, which is focused on functions.

A class is a template from which you can then create multiple objects, with similar characteristics.

A class is a template, which defines properties (variables) and methods (functions)

The class defines properties and methods common to objects of that type, but then, each object will have its own values and share the same functions.

We must create a class before we can create objects (instances) of that class. When creating an object of a class, it is said that an instance of the class or an object itself is created.

The basic structure in Kotlin of a class is:

Class [class name] { 
  [class properties] 
  [ class methods or functions] 
}

Problem 1

We will implement a class called Person whose properties (variables) will be their name and age, and three methods (functions), one of these methods will initialize the properties of the name and age, another method will show on the screen the contents of properties and Last one you print if you are of legal age.

Define two objects in the Person class.

Project109 – Principal.kt

class Person {
    var name: String = ""
    var age: Int = 0

    fun initialize (name: String, age: Int) {
        this.name = name
        this.age = age
    }

    fun print () {
        println ( "Name: $name and has an age of $age ")
    }

    fun isMayorage () {
        if (age>= 18)
        println ("Yes Is of age $name ")
        else
        println ("No Is not of age $name ")
    }
}

fun main (parameter: Array <String>) {
    val person1: Person
    person1 = Person ()
    person1.initialize ("Juan",12)
    person1.print ()
    person1.isMayorage ()
    val person2: Person
    person2 = Person ()
    person2.initialize ("Ana", 50)
    person2.print ()
    person2.isMayorage ()
}

The name of the class must refer to the concept (in this case we have called it Person). The keyword to declare the class is class, then the class name and then an opening key that must be closed at the end of the class declaration:

Class Person {

We define two properties called name and age, initialize them with an empty String to one and with 0 to the other:

    Var name: String = "" 
    var age: Int = 0

One of the premises of the Kotlin language is that it is safe and does not allow to define a property and not assign a value and that is with the value null

Then we define its three methods (it is what we know as functions until now, but being inside a class are called methods)

The initialize method receives as parameters a String and an Int in order to load the properties name and age:

    Fun initialize (name: String, age: Int) { 
        this.name = name 
        this.age = age 
    }

As the parameters are called in this case just as the properties differentiate them by preceding the keyword this to the name of the property:

        This.name = name 
        this.age = age

The print method aims to show the content of the two properties:

    Fun print () { 
        println ("Name: $name and has an age of $age") 
    }

As in this method, there are no parameters that are called equal to the properties we can access the properties directly by their name and not be forced to proceed this operator, there would be no problem to precede this and write this:

    fun print () { 
        println ("Name: ${this.name} and has an age of ${this.age}") 
    }

The third and final method is intended to show a message whether the person is of legal age or not:

    fun isMayorage () { 
        if (age >= 18) 
            println ( "adult is $name") 
        else 
            println ( "No age is over $name") 
    }

We said that a class is a mold that allows us to create objects. Now let’s see what the syntax is for creating objects in the Person class:

fun main (parameter: Array <String>) { 
    val person1: Person 
    person1 = Person () 
    person1.initialize ("John", 12) 
    person1.print ()
    person1.isMayorage()

First we must define a variable of type Person:

    Val persona1: Person

To create the object we must assign the variable person1 the name of the class and open and closed parentheses:

    Person1 = Person ()

Once we have created the object we can call its methods by first preceding the name of the object (person1):

    Person1.initialize ("Juan", 12) 
    person1.print () 
    person1.isMayorage ()

It is important the order that we call the methods, for example, if we first call to print before initializing, we will see that it shows an age of zero and an empty String as a name.

A class is a template that allows us to create as many objects as we need, in our problem we must create two objects of the Person class, the second we create it in a similar way to the first:

    Val person2: Person 
    person2 = Person () 
    person2.initialize ("Ana", 50) 
    person2.print () 
    persona2.isMayorage ()

Dimensioning.

We have seen that Kotlin seeks to be concise, we can in a single line define the object and create it with the following syntax:

    Val person1 = Person ()

Instead of:

    Val person1: Person 
    person1 = Person ()

This should remind us of earlier concepts when defining an object of class Int:

    Val weight: Int 
    weight = 40

And we concisely write:

    Val weight = 40

Problem 2

Implement a class that loads the sides of a triangle and implement the following methods: initialize the properties, print the value of the major side and another method that shows whether it is equilateral or not.

Project110 – Main.kt

class Triangle {
    var side1: Int = 0
    var side2: Int = 0
    var side3: Int = 0

    fun initialize() {
        print("Enter side 1:")
        side1 = readLine()!!.toInt()
        print("Enter side 2:")
        side2 = readLine()!!.toInt()
        print("Enter side 3:")
        side3 = readLine()!!.toInt()
    }

    fun LoadMayor() {
        print("Top side:")
        when {
            side1 > side2 && side1 > side3 -> println(side1)
            side2 > side3 -> println(side2)
            else -> println(side3)
        }
    }

    fun isequilateral() {
        if (side1 == side2 && side1 == side3)
            print("It is an equilateral triangle")
        else
            print("Not an equilateral triangle")
    }
}


fun main (parameter: Array <String>) {
    val triangle1 = Triangle ()
    triangle1. initialize ()
    triangle1.LoadMayor ()
    triangle1.isequilateral ()
}

The Triangle class defines three properties where we store the sides of the triangle:

Class Triangle { 
    var side1: Int = 0 
    var side2: Int = 0 
    var side3: Int = 0

The initialize method, which we must remember to be the first to be called, proceeds to load the three sides of the triangle by keyboard:

    fun initialize () { 
        print ( "Enter side 1") 
        side1 = readLine () !! toint (). 
        print ( "Enter side 2") 
        . side2 = readLine () !! Toint () 
        print ( "Enter side 3: ") 
        side3 = readLine () !!. ToInt () 
    }

The second method checks which of the three sides has a higher value stored using the when statement (instead of a series of nested if):

fun LoadMayor() {
    print("Top side:")
    when {
        side1 > side2 && side1 > side3 -> println(side1)
        side2 > side3 -> println(side2)
        else -> println(side3)
    }
}

The third method verifies if it is an equilateral triangle:

 fun isequilateral() {
        if (side1 == side2 && side1 == side3)
            print("It is an equilateral triangle")
        else
            print("Not an equilateral triangle")
    }

In the main function we define an object of the Triangle class and call its methods:

fun main (parameter: Array <String>) {
    val triangle1 = Triangle ()
    triangle1. initialize ()
    triangle1.LoadMayor ()
    triangle1.isequilateral ()
}

Proposed problem

  • Implement a class called Student that has properties like its name and its note. Define methods to initialize their properties by keyboard, print them and display a message if it is regular (note greater than or equal to 4)
    Define two objects in the Student class.
Project111 
class Student {
    var name: String = ""
    var note: Int = 0

    fun initialize () {
        print ("Enter the student's name:")
        name = readLine () !!. toString ()
        print ("Enter your note:")
        note = readLine () !!. toInt ()
    }

    fun print () {
        println ("Student: $name has a $note")
    }

    fun showState () {
        if (note>= 4)
        println ("$name is in REGULAR state")
        else
        println ("$name is not REGULAR")
    }
}

fun main (Parameters: Array <String>) {
    val Student1 = Student ()
    Student1.initialize()
    Student1.print()
    Student1.showState()
    val Student2 = Student ()
    Student2.initialize()
    Student2.print()
    Student2.showState()

}

 

About The Author

Related posts

Leave a Reply