Kotlin Tutorial - 7 Class and Object

nadirbasalamah

nadirbasalamah

Posted on October 7, 2021

Kotlin Tutorial - 7 Class and Object

Object oriented programming is a programming paradigm that mainly focused on real life entities like human, car and abstract entity like course that taken by student. Object oriented programming usually involves an entity that represented as a class with attributes like name, age and behavior in entity like walk.

Create Class and Object

In object oriented programming, class is a blueprint that used to create an object. In Kotlin, a class can be created using this syntax.

class class_name(
    attributes,...
) {
    // behaviors...
}
Enter fullscreen mode Exit fullscreen mode

This is the example of class creation. The class called Student is created to represents a student entity. This class is created in separated file Student.kt.

// create Student class with name and course as attribute
class Student(
    val name: String,
    val course: String
) {
    // create learn method
    fun learn() {
        println("learning $course")
    }
}
Enter fullscreen mode Exit fullscreen mode

The Student class is used inside main() method.

fun main() {
    // create an object from Student class
    val student = Student("john doe","Algorithm")

    // call learn() method from the object
    student.learn()
}
Enter fullscreen mode Exit fullscreen mode

Output

learning Algorithm

Enter fullscreen mode Exit fullscreen mode

Based on the code above, a class called Student is created inside Student.kt file then the object from Student class is created by using constructor from Student class with the specified values for attributes. The learn() method can be called from the created object.

The best practice for class usage is to create a class in a separated file so the refactoring or maintenance for certain class can be done easily.

If the object is created from the class then the attribute value can be changed after the object is created. Use var keyword for certain attribute in a class.

// create Student class with name and course as attribute
class Student(
    var name: String,
    var course: String
) {
    // create learn method
    fun learn() {
        println("learning $course")
    }
}
Enter fullscreen mode Exit fullscreen mode

The attribute value for course is changed.

fun main() {
    // create an object from Student class
    val student = Student("john doe","Algorithm")

    // the course value is changed
    student.course = "Algorithm with C++"

    // call learn() method from the object
    student.learn()
}
Enter fullscreen mode Exit fullscreen mode

Output

learning Algorithm with C++

Enter fullscreen mode Exit fullscreen mode

Create Data Class

In Kotlin, there is a specific class to create a particular object class or also known as POJO (Plain Old Java Object) by using data class. The POJO class is a class that contains particular methods including setter and getter.

This is the basic syntax to create data class.

data class class_name(
    attributes,...
)
Enter fullscreen mode Exit fullscreen mode

This is the example of data class usage for course entity. This class is created in Course.kt file.

// create a data class called Course
data class Course(
    val code: String,
    val name: String
)
Enter fullscreen mode Exit fullscreen mode

The object from Course class is created in main() method.

fun main() {
    // create an object from Course class
    val course = Course("C001","Data Structure")

    // print out the course data
    println("Course data")
    println("Course code: ${course.code}")
    println("Course name: ${course.name}")
}
Enter fullscreen mode Exit fullscreen mode

Output

Course data
Course code: C001
Course name: Data Structure

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the object from Course class is created by using constructor from Course class that filled with specified values for the attributes.

If the object is created using data class, the attribute value from certain object can be retrieved with destructuring mechanism.

This is the example of destructuring mechanism.

fun main() {
    // create an object from Course class
    val course = Course("C001", "Kotlin Basics")

    // perform destructuring
    // retrieve value from attributes (code and name)
    val (code, name) = course

    // print out the value from code and name attribute
    println("Course data")
    println("Code: $code")
    println("Name: $name")
}
Enter fullscreen mode Exit fullscreen mode

Output

Course data
Code: C001
Name: Kotlin Basics

Enter fullscreen mode Exit fullscreen mode

toString() Method

The toString() method can be used to give the information of created object from certain class. This is the example of toString() method usage in Course class.

// create a data class called Course
data class Course(
    val code: String,
    val name: String
) {
    // using toString() method
    override fun toString(): String {
        return "Course(code='$code', name='$name')"
    }
}
Enter fullscreen mode Exit fullscreen mode

The object from Course class is created in main() method.

fun main() {
    // create an object from Course class
    val course = Course("C001", "Kotlin Basics")

    // print out the object information
    println("Course data: $course")
}
Enter fullscreen mode Exit fullscreen mode

Output

Course data: Course(code='C001', name='Kotlin Basics')

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the toString() method is called automatically if the course object is printed out.

Special Class in Kotlin (object)

In Kotlin there is a specific class for one time use called object. An object can be created directly in a variable or in a separated file.

This is the example of creating object directly in a variable.

fun main() {
    // create an "object" class in person variable
    val person = object {
        val name = "joe"
        val address = "palm city"

        fun greet() {
            println("Hi, my name is $name")
            println("I lived in $address")
        }
    }

    // object can be used directly
    // without creation or instantiation
    person.greet()
}
Enter fullscreen mode Exit fullscreen mode

Output

Hi, my name is joe
I lived in palm city

Enter fullscreen mode Exit fullscreen mode

Based on the code above, an object is created directly inside person variable. The object can be used directly without creation or instantiation of an object class.

In this example, the object class is created in separated file called Person.kt.

object Person {
    val name = "nathan mckane"
    val address = "rockford"

    fun greet() {
        println("Hi, my name is $name")
        println("I lived in $address")
    }

    fun say(message: String) {
        println("$name says $message")
    }
}
Enter fullscreen mode Exit fullscreen mode

The object that already created is used in main() method.

fun main() {
    // using Person "object" in variable
    val person = Person
    person.greet()

    // the Person "object" can be used directly
    Person.say("hello!")
}
Enter fullscreen mode Exit fullscreen mode

Output

Hi, my name is nathan mckane
I lived in rockford
nathan mckane says hello!

Enter fullscreen mode Exit fullscreen mode

Based on the code above, an object called Person can be used inside variable or use the object directly.

The companion object can be used in a class if the method or attribute can be accessed directly without creating an object from certain class. In this example, the companion object is used in Calculator class.

class Calculator {
    // create companion object
    companion object {
        // these methods can be accessed directly
        // without creating an object from Calculator class
        fun sum(x: Int, y: Int): Int {
            return x + y
        }

        fun multiply(x: Int, y: Int): Int {
            return x * y
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The Calculator class is used in main() method.

fun main() {
    // the sum and multiply method called directly
    // from Calculator class
    val sumResult: Int = Calculator.sum(4,5)
    val multiplyResult: Int = Calculator.multiply(5,6)

    println("Result from sum operation: $sumResult")
    println("Result from multiply operation: $multiplyResult")
}
Enter fullscreen mode Exit fullscreen mode

Output

Result from sum operation: 9
Result from multiply operation: 30
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the sum() and multiply() method can be accessed directly from Calculator class because these methods are created inside companion object.

Generic

The generic concept is also available in Kotlin. Generic is a mechanism when a data type acts as parameter in a class. Generic can be used to define which data type is used in certain class rather than make some classes for many data types.

This is the example of generic usage in Kotlin.

class Box<T>(val content: T)
Enter fullscreen mode Exit fullscreen mode

Create an object from Box class that use generic.

fun main() {
    val stringBox: Box<String> = Box("cool!")
    val intBox: Box<Int> = Box(24)

    println("Content from stringBox: ${stringBox.content}")
    println("Content from intBox: ${intBox.content}")
}
Enter fullscreen mode Exit fullscreen mode

Output

Content from stringBox: cool!
Content from intBox: 24
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the generic is used inside angle brackets <> with T notation for generic type.

Enum

Enum is a class that contains many constants. This is the basic syntax to create an enum.

enum class enum_name {
    VALUE1, VALUE2, ...
}
Enter fullscreen mode Exit fullscreen mode

In this example, an enum is created called Role.

enum class Role {
    STUDENT, LECTURER, ADMIN
}
Enter fullscreen mode Exit fullscreen mode

The value from Role enum is used inside Student class.

// create Student class
class Student(
    val name: String,
    val course: String,
    // using value from Role enum
    val role: Role = Role.STUDENT,
) {
    fun learn() {
        println("Learning $course")
    }

}
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the value from Role enum is used inside an attribute with Role data type.

Notes

  • Class is a blueprint for an object.

  • Data class is suitable to create a particular object that contains setter and getter method.

  • The object class can be used only once.

  • Enum is suitable to store many constants

Sources

  • Learn more about class in this link.

  • Learn more about data class in this link.

  • Learn more about object in this link.

  • Learn more about generic in Kotlin in this link.

  • Learn more about enum in this link.

I hope this article is helpful for learning the Kotlin programming language. If you have any thoughts or comments you can write in the discussion section below.

💖 💪 🙅 🚩
nadirbasalamah
nadirbasalamah

Posted on October 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related