Lesson 25: – Object Oriented Programming – Class Builder in kotlin

Lesson 25: – Object Oriented Programming – Class Builder in kotlin

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

In Kotlin we can define a method that is executed initially and automatically. This method is called constructor.

Kotlin constructor has the following characteristics:

  • It is the first method to be executed.
  • It runs automatically.
  • Can not return data.
  • It runs only once.
  • A constructor aims to initialize attributes.
  • A class may have several constructors but only one is the principal.

Problem 1

Implement a class called Person that will have properties like their name and age.
Ask a builder where the name and age should come as parameters.
Define in addition two methods, one that prints the properties and another shows if it is of age.

Project112 – Principal.kt

class Person constructor (name: String, age: Int) {
    var name: String = name
    var age: Int = age

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

    fun isMayorage () {
        if (age >= 18)
        println ("Is an adult $name")
        else
        println ("You are not of age $name")
    }
}

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

The main constructor of the class declares it immediately after defining the name of the class:

Class Person constructor (name: String, age: Int) {

We can see that it does not have a block of keys with code and we can assign the parameters to properties that define the class:

    Var name: String = name
    Age: Int = age

In the main function where we define an object of the Person class we must pass in a mandatory form the data that the constructor receives:

    Val person1 = Person ("Jan", 12)

That is why we say that the constructor runs automatically and aims to initialize properties of the object being created.

The call to the other methods of the class does not change anything as seen in the previous concept:

    person1.print()
    Person1.isMajorAge ()

Optional builder keyword in Kotlin.

In many situations like this the keyword constructor is optional and in a more concise way we can write the declaration of the class and its main constructor with the syntax:

Class Person (name: String, age: Int) {

We will see in future concepts that the word constructor is mandatory when we add a modifier of access (private, protected, public, internal) before the constructor or an annotation.

Definition of properties in the same constructor in Kotlin.

This is also implemented by Kotlin to make the program as concise as possible (reducing the number of lines of code)

The complete program now has the syntax:

class Person (var name: String, var age: Int) {

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

    fun isMayorage () {
        if (age >= 18)
        println ("Is an adult $name")
        else
        println ("You are not of age $name")
    }
}

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

It is important to see that when we declare the constructor we have defined the two properties:

Class Person (var name: String, var age: Int) {

You do not have to declare them inside the class and if we do it generates a syntactic error since we will be defining twice with the same name a property:

Class Person (var name: String, var age: Int) {
   Var name: String = ""
   Var age: Int = 0

This does not mean that other properties in the class are not going to be defined, only the ones that are initialized in the constructor are defined in the class.

Init block in kotlin language

If in some situations we want to execute an algorithm immediately after the constructor we must implement a block called init.

In this block we can, for example, validate the data that arrives at the constructor and initialize other properties of the class.

We will modify the program again to verify if the parameter of the age reaches a value less than zero:

class person (var name: String, var age: Int) {

    init {
        if (age <0)
            age = 0
    }

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

    fun MayorAge () {
        if (age >= 18)
        println ("is an adult $name")
        else
        println ("You are not of age $name")
    }
}

fun main (parameter: Array <String>) {
    val person1 = person ("Juan", -12)
    person1.print ()
    person1.MayorAge ()
}

The init block must be enclosed in braces and implemented an algorithm that will be executed immediately after the constructor. In our example, if the property “age” is loading a negative value we proceed to assign a zero:

    Init {
        If (age <0)
            Age = 0
    }

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.

Project113 – Principal.kt

class triangle (var side1: Int, var side2: Int, var side3: Int) {

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

    fun equilateral(){

    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 (12, 45, 24)
    triangle1.loadMajor ()
    triangle1.equilateral()
}

We define three properties in the main constructor of the class:

class Triangle (var side1: Int, var side2: Int, var side3: Int) {

When we create an object of the Triangle class in the main function we pass the values of the three sides of the triangle:

fun main (parameter: Array <String>) {
    val triangle1 = Triangle (12, 45, 24)
    triangulo1.loadMajor ()
    triangulo1.equilateral() 
}

Definition of several constructors in Kotlin Language

When defining another constructor besides the principal of the class, Class must be implemented with the constructor keyword, its parameters and the mandatory call to the main constructor of the class. In a block of keys, we develop the algorithm of the same.

Problem 3

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.

Point the main constructor that receives the values of the sides and a second constructor that allows entering by keyboard the three sides.

Project114 – Principal.kt

class triangle (var side1: Int, var side2: Int, var side3: Int) {

    constructor (): this (0, 0, 0) {
        print ("Enter first side:")
        side1 = readLine () !!. toInt ()
        print ("Enter second side:")
        side2 = readLine () !!. toInt ()
        print ("Enter third side:")
        side3 = readLine () !!. toInt ()
    }

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

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

fun main (parameter: Array <String>) {
    val triangle1 = triangle ()
    triangle1.loadMajor()
    triangle1.equilateral ()
    val triangle2 = triangle (6, 6, 6)
    triangle2.loadMajor()
    triangle2.equilateral()
}

The main constructor with the definition of three properties is:

Class Triangle (var side1: Int, var side2: Int, var side3: Int) {

The second constructor must call the main constructor by preceding the keyword this and in parentheses the data to be sent:

    Constructor (): this (0, 0, 0) {

Then between braces the algorithm itself of that constructor:

    Constructor (): this (0, 0, 0) {
        Print ("Enter first side:")
        Side1 = readLine () !!. ToInt ()
        Print ("Enter second side:")
        Side2 = readLine () !!. ToInt ()
        Print ("Enter third side:")
        Side3 = readLine () !!. ToInt ()    
    }

Now when we create an object from the Triangle class we can call one or another constructor according to our needs.

If we want to load the three sides of the triangle by keyboard, we must call the constructor that has no parameters:

Val triangle1 = Triangle ()
    Triangle1.loadMajor ()
    Triangle1.equilateral()

If we already know the values of each side of the triangle we pass them in the call to the constructor:

    Val triangle2 = Triangle (6, 6, 6)
    Triangle2.loadMajor ()
    Triangle2.equilateral()

Problems proposed

  • Implement a class called Student that has properties like its name and its note. The builder gets his name and note.
    Print the name and your note. Display a message if it is regular (note greater than or equal to 4)
    Define two objects in the Student class.
  • Compound a class that represents a point in the plane, the coordinate of a point in the plane is given by two integer values x and y.
    The constructor arrives at the location of the point at x and y.
    Implement a method that returns a String that indicates in which quadrant that point is located. (1 Quadrant if x> 0 Y y> 0, 2º Quadrant: x <0 Y y> 0, 3º Quadrant: x <0 Y y <0 Quadrant: x> 0 Y y <0)
    If any or both Values are zero then the point is on an axis.
    Then define 5 objects of the Point class in each of the quadrants and one on an axis.

Solution

class student (val name: String, val note: Int) {

    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 ("Ana", 7)
    student1.print ()
    student1.showState()
    
    val student2 = student ("Carlos", 2)
    student2.print ()
    student2.showState()
}

...........



class Point (val x: Int, val y: Int) {

    fun returnCurrent () = when {
        x > 0 && y> 0 -> "First quadrate"
        x <0 && y> 0 -> "Second quadrant"
        x <0 && y <0 -> "Third quadrant"
        x > 0 && y <0 -> "Fourth quadrant"
        else -> "One axis"
    }
}

fun main (parameter: Array <String>) {
    val point1 = Point (12, 3)
    println ("The coordinate $ {point1.x}, ${point1.y} is in ${point1.returnCurrent ()}")
    val point2 = Point (-4, 3)
    println ("The coordinate $ {point2.x}, ${point2.y} is located in ${point2.returnCurrent ()}")
    val point3 = Point (-2, -2)
    println ("The coordinate ${point3.x}, ${point3.y} is located in ${point3.returnCurrent ()}")
    val point4 = Point (12, -5)
    println ("The coordinate ${point4.x}, ${point4.y} is located in ${point4.returnCurrent ()}")
    val point5 = Point (0, -5)
    println ("The coordinate ${point5.x}, ${point5.y} is located in ${point5.returnCurrent ()}")
}

 

About The Author

Related posts

Leave a Reply