Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Kotlin in Android Studio 3.0 (Part 3)

DZone's Guide to

Using Kotlin in Android Studio 3.0 (Part 3)

Learn more about using Kotlin to develop for Android by looking at object-oriented programming concepts.

· Mobile Zone ·
Free Resource

Object-Oriented Programming (OOP)

Class

In Java, we have become so familiar with OOP. The most important concepts in OOP are “class” and “object.” A class and its members can look like this:

Image title

In Kotlin, a class is declared by the  class  keyword and followed by the class name. Members of the class, such as fields and properties, are declared in curly brackets blocks like the following example:

class Person
{
      // members of Person
}

Property and Field

In Java, a field is a data member of a class and can be declared like a variable. A field can only be accessed through a property. Properties represent an important feature of OOP - encapsulation.

In Kotlin, properties are the equivalent to fields in Java but much more powerful. A property, in Kotlin, is a combination of a field, a setter, and a getter. Fields cannot be declared directly in Kotlin classes but when a property needs a backing field, Kotlin provides it automatically by using the  field  identifier. The following example will demonstrate declaring the Name property and using the backing field:

class Person
{
    // declaring Name property and using the backing field
    var Name:String = ""
    get() = field.toUpperCase()
    set(value){
        field="I am $value"
    }
    ...
}

Constructors

Classes have a unique default constructor, however, we can create extra constructors for some exceptional cases. Parameters of a constructor are written just after the name and its body can be declared in a  Init  block. Let’s look at an example:

class Person(name: String, surname: String) {
init {
 // body of the constructor
         }
}

Methods

Kotlin methods are functions (as I have mentioned in Part 2). An example looks like this:

class Person
{
    // declaring Name property and using the backing field
 var Name:String = ""
    get() = field.toUpperCase()
    set(value){
        field="I am $value"
    }
   // declaring a method
fun canWork():String = "I can unknown!"
}

Visibility Modifiers

There are four visibility modifiers in Kotlin:  public ,  private ,  protected  and  internal . The default visibility, used if there is no explicit modifier, is public .

Instances or Objects

To create an instance (or object) of a class, we call the constructor as if it is a regular function and we also note that, Kotlin does not have a new keyword as the following example:

val person = Person()

Class Inheritance

Classes are closed by default, so we can only extend a class if it’s explicitly declared as  open  or  abstract . An example:

open class Person
{
   ...
}

class Student: Person()
{
   ...
}

We can override members, such as methods, properties, of a parent class in subclasses by using the  open  keyword (in parent class) and  override  keyword (in subclasses). In the following example, we overrode the canWork() method in the Student class:

open class Person
{
     ...
     open fun canWork():String = "I can unknown!"
}
class Student: Person()
{
     ...
     override fun canWork(): String {
          return "I can learn."
    }
}

This feature called is polymorphism in OPP.

An Android Application

In this article, my application has a UI as follows:

Image title

Some controls used in this UI application can be demonstrated in the following table:

Control

ID attribute

Text attribute

EditText

txtID

@string/id

EditText

txtName

@string/name

EditText

txtUni

@string/university

RadioButton

rdMale

@string/male

RadioButton

rdFemale

@string/female

RadioGroup

gender


TextView

textView

Gender

TextView

data


The source code of the strings.xml file and main_activity.xml file is here.

My application contains three classes: MainActivity class, Person class and Student class that is inherited from Person class. My application model can look like this:

Image title

The Person and Student classes contain their members (properties, method) as in the following figure:

Image title

I have declared the Person and Student classes in MainActivity.kt file as follows:

open class Person
{
    var Name:String = ""
    get() = field.toUpperCase()
    set(value){
        field="I am $value"
    }
    var Gender:String=""
    open fun canWork():String = "I can unknown!"
}
class Student:Person()
{
    var StudentID:String = ""
    var University:String=""
    override fun canWork(): String {
        return "$Name .I am learning at $University. My ID is $StudentID and my gender is $Gender \n"
    }
}

We can enter some data from the interface of the application and store them in a Student object by using the dataOf() function as follows:

fun dataOf(student:Student):String
{
    student.StudentID = txtID.text.toString()
    student.Name = txtName.text.toString()
    student.University = txtUni.text.toString()
    student.Gender = if(rdMale.isChecked)"Male" else "Female"
    return student.canWork()
}

The complete code of the MainActivity.kt file can look like this:

package com.example.admin.myfirstkotlinapp
import android.view.View
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var s =""
        val buttonClickListener = View.OnClickListener { view ->

            var student = Student()
            s += dataOf(student)
            data.text = s
            txtID.text.clear()
            txtName.text.clear()
            txtUni.text.clear()
            rdFemale.isChecked = true
            rdMale.isChecked = false
        }

        btnData.setOnClickListener(buttonClickListener)
    }
    fun dataOf(student:Student):String
    {
        student.StudentID = txtID.text.toString()
        student.Name = txtName.text.toString()
        student.University = txtUni.text.toString()
        student.Gender = if(rdMale.isChecked)"Male" else "Female"

        return student.canWork()
    }

}
open class Person
{
    var Name:String = ""
    get() = field.toUpperCase()
    set(value){
        field="I am $value"
    }
    var Gender:String=""

    open fun canWork():String = "I can unknown!"
}

class Student:Person()
{
    var StudentID:String = ""
    var University:String=""
    override fun canWork(): String {
        return "$Name .I am learning at $University. My ID is $StudentID and my gender is $Gender \n"
    }
}

Run the application and enter data for the first Student object:

Image title

Click the Data button:

Image title

Enter the data for the second Student object:

Image title

Click the Data button:

Image title

Conclusion

In this article, I have introduced aspects of object-oriented programming for Kotlin. You can download my source code here and I hope you have a great experience.

Topics:
android ,mobile ,mobile app development ,kotlin

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}