lesson 33: OOP – inheritance in Kotlin Language

lesson 33: OOP – inheritance 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

We saw in previous concepts that two classes can be related by the collaboration (in one of them we define a property of the type of the other class). Now we will see another type of relationship between classes that is the Inheritance.

Inheritance means that you can create new classes from existing classes, which will have all the properties and methods of your ‘superclass’ or ‘parent class’ and you can also add other properties and methods of your own.

Father class

Class from which a class descends or drifts. Daughter classes (descendants) automatically inherit (incorporate) the properties and methods of the parent class.

Subclass

Descending class of another. It automatically inherits the attributes and methods of its superclass. It is a specialization of another kind.
They allow the definition of new attributes and methods to increase the specialization of the class.

Let’s look at some theoretical examples of inheritance:

1) Imagine the class Vehicle. What classes could be derived from it?

                            Vehicle

   Motorcycle
                             
                                             FordK Renault Fluence

Always down in the hierarchy there is a specialization (subclasses add new properties and methods.

2) Imagine the Software class. What classes could be derived from it?

                                           software

             DeApplication DeBase

ProcessorTextObject CalculationOperative System

Word WordPerfect Excel Lotus123 Linux Windows       

The first type of relationship that we had seen between two classes, is the one of collaboration. Recall that is when a class contains an object of another class as an attribute.
When the relationship between two classes is of the type “… has a …” or “… is part of …”, we should not implement inheritance. We are facing a collaborative class relationship not of inheritance.

If we have a ClassA and another ClassB and note that there is a relationship of type “… has a …”, we must not implement inheritance but declare in class ClassA an attribute of class ClassB.

For example: we have an Auto class, a Wheel class, and a Steering class. We see that the relationship between them is: Auto “… has 4 …” Wheel, Steering wheel “… is part of …” Auto; But the Auto class should not be derived from Wheel or Auto Steering wheel because the relationship is not of type-subtype but of collaboration. We must declare in the Auto class 4 Wheel attributes and 1 Wheel type attributes.

Then if we see that two classes answer the question ClassA “..is a ..” ClassB it is possible that there is a relation of inheritance.

For example:

Auto "is a" Vehicle "
Circle "is a" Figure
Mouse "is a" Input Device
Sum "is a" Operation

Problem 1:

Raise a class Person that contains two properties: name and age. Define as responsibilities the builder who receives the name and age.
In the main function of the program define an object of the Person class and call its methods.

Declare a second class called Employee who inherits from the Person class and add a wage property and show if you must pay taxes (salary greater than 3000)
Also in the main function of the program create an object of class Employee.

Project137 – Principal.kt

open class Person (val name: String, val age: Int) {
    open fun print () {
        println ("Name: $name")
        println ("Age: $age")
    }
}

class Employee (name: String, age: Int, val salary: Double): Person (name, age) {
    override fun print () {
        super.print ()
        println ("Salary: $salary")
    }

    fun paidtaxes () {
        if (salary > 3000)
            println ("Employee $name pays taxes")
        else
            println ("The employee $name does not pay taxes")
    }
}

fun main (parameter: Array <String>) {
    val person1 = Person ("Jose", 22)
    println ("Data of the person")
    person1.print()

    val employee1 = Employee ("Ana", 30, 5000.0)
    println ("Employee Data")
    employee1.print ()
    employee1.paidtaxes()
}

In Kotlin for a class to be inheritable we must precede the open keyword before class:

Open class Person (val name: String, val age: Int) {

When a programmer defines an open class, the definition of its properties and methods must be seriously considered.

If we want a method to be rewritten in a subclass we must precede the keyword open:

    Open fun print () {
        Println ("Name: $name")
        Println ("Age: $age")
    }

When we define an object of the Person class in the main function but it is open and has open methods does not change at all to how we define objects and access their properties and methods:

Fun main (parameter: Array <String>) {
    Val person1 = Person ("Jose", 22)
    Println ("Data of the person")
    person1.Print()

The new appears when we declare the Employee class that receives three parameters, it is important to note that in the third we are defining a property called salary (because we precede the keyword val)

The inheritance is indicated after the colon indicating the name of the class from which we inherit and immediately passing the data of the constructor of that class:

Class Employee (name: String, age: Int, val salary: Double): Person (name, age) {

We can say that the Employee class has three properties (name, age and salary), one own and two inherited.

As we do not precede the keyword open to the class declaration then we can not declare classes that inherit from the class Employee. If we want the Employee class to inherit other classes we must define it with the syntax:

Open class Employee (name: String, age: Int, val salary: Double): Person (name, age) {

The Employee class other than the constructor defines two methods, one that prints a message if the employee should be taxed:

    Fun paid taxes () {
        If (salary> 3000)
            Println ("Employee $name pays taxes")
        Else
            Println ("The employee $name does not pay taxes")
    }

The print method indicates using the override keyword that we are overwriting the print method of the person class (inside the print method we can call the print method of the parent class preceding the super keyword):

    Override fun print () {
        Super.print ()
        Println ("Salary: $salary")
    }

With the call to the printing method of the inheritance class we can display all employee data which is your name, age and salary.

To define an object of class Employee in the main function we do with the syntax that we already know:

    Val employee1 = Employee ("Ana", 30, 5000.0)
    Println ("Employee Data")
    Employee1.print ()
    Employee1.paidtaxes()

Problem 2:

Declare a class called Calculator that receives two values of type Double in the constructor. Make the class open to be inheritable
Define the responsibilities of adding, subtracting, multiplying, dividing and printing.

Then declare a class called CalculatorCalculate that inherits from Calculator and add the responsibilities of calculating the square of the first number and the square root.

Project138 – Principal.kt

open class calculator (val value1: Double, val value2: Double) {
    var result: Double = 0.0
    fun sum () {
        result = value1 + value2
    }

    fun sub () {
        result = value1 - value2
    }

    fun multiply () {
        result = value1 * value2
    }

    fun divide () {
        result = value1 / value2
    }

    fun print () {
        println ("Result: $result")
    }
}

class ScientificCalculator (value1: Double, value2: Double): calculator (value1, value2) {
    fun square () {
        result = value1 * value1
    }

    fun root () {
        result = Math.sqrt (value1)
    }
}

fun main (parameter: Array <String>) {
    println ("class test Calculator(sum of two numbers)")
    val calculator1 = calculator (10.0, 2.0)
    calculator1.sum ()
    calculator1.print ()

    println ("Test of Scientific Calculator class (sum of two numbers and the square and root of the first)")
    val ScientificCalculator1 = ScientificCalculator (10.0, 2.0)
    ScientificCalculator1.sum ()
    ScientificCalculator1.print ()

    ScientificCalculator1.square ()
    ScientificCalculator1.print ()

    ScientificCalculator1.root ()
    ScientificCalculator1.print ()
}

We declare the class Calculator open to allow other classes to inherit from this, two values of type Double arrive at the constructor:

Open class Calculator (val value1: Double, val value2: Double) {

We define a third property called result also double:

    Var result: Double = 0.0

It is important to note that the result property is public, then we can have access in its subclasses. If we define the type private then the subclass Scientific Calculator can not access its content:

    Private var result: Double = 0.0

In the ScientificCalculator class, a syntax error is generated when we want to access the property:

    Fun square () {
        Result = value1 * value1
    }

We saw that the access modifiers can be public (this is the default value) and private, there is a third access modifier named protected that allows a subclass to access the property but does not have access from where we define an object of said class. Then the most convenient for this problem is to define the result property of protected type:

    Protected var result: Double = 0.0

The Calculator class defines the four methods with the basic operations and printing the result.

The CalculatorCalculation class inherits from the Calculator class:

Class ScientificCalculator (value1: Double, value2: Double): Calculator (value1, value2) {

A scientific calculator apart from the four basic operations adds the possibility of calculating the square and the root of a number:

    Fun square () {
        Result = value1 * value1
    }

    Fun root () {
        Result = Math.sqrt (value1)
    }

In the main function we create an object from the Calculator class and call several of its methods:

Fun main (parameter: Array <String>) {
    Println ("Calculator class test calculator(sum of two numbers)")
    Val calculator1 = Calculator (10.0, 2.0)
    Calculator1.sum ()
    Calculator1.print ()

We do the same thing by defining an object of the Class CalculatorCientificate and calling some of its methods:

    Println ("Test of Scientific Calculator class (sum of two numbers and the square and root of the first)")
    Val ScientificCalculator1 = ScientificCalculator (10.0, 2.0)
    ScientificCalculator1.sum ()
    ScientificCalculator.print ()
    Scientificcalculator.Square ()
    ScientificCalculator1.print ()
    ScientificCalculator1.root ()
    ScientificCalculator1.print ()

Proposed problem

  • Declaring a class Since it generates a random value between 1 and 6, display its value.
    Create a second class named DataDate that generates a value between 1 and 6, show the value set in asterisks.
    Use inheritance between these two classes.
Solution

 

About The Author

Related posts

Leave a Reply