Kotlin Tutorial - 7 Class and Object
Tags: kotlin, beginners, tutorial
Published: 2021-10-07 01:22:34

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...
}
```

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`.

```kotlin
// 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")
    }
}
```

The `Student` class is used inside `main()` method.

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

    // call learn() method from the object
    student.learn()
}
```

Output

```
learning Algorithm

```

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.

```kotlin
// 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")
    }
}
```

The attribute value for `course` is changed.

```kotlin
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()
}
```

Output

```
learning Algorithm with C++

```

## 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,...
)
```

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

```kotlin
// create a data class called Course
data class Course(
    val code: String,
    val name: String
)
```

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

```kotlin
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}")
}
```

Output

```
Course data
Course code: C001
Course name: Data Structure

```

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.

```kotlin
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")
}
```

Output

```
Course data
Code: C001
Name: Kotlin Basics

```

## `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.

```kotlin
// 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')"
    }
}
```

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

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

    // print out the object information
    println("Course data: $course")
}
```

Output

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

```

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.

```kotlin
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()
}
```

Output

```
Hi, my name is joe
I lived in palm city

```

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`.

```kotlin
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")
    }
}
```

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

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

    // the Person "object" can be used directly
    Person.say("hello!")
}
```

Output

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

```

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.

```kotlin
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
        }
    }
}
```

The `Calculator` class is used in `main()` method.

```kotlin
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")
}
```

Output

```
Result from sum operation: 9
Result from multiply operation: 30
```

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.

```kotlin
class Box<T>(val content: T)
```

Create an object from `Box` class that use generic.

```kotlin
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}")
}
```

Output

```
Content from stringBox: cool!
Content from intBox: 24
```

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, ...
}
```

In this example, an enum is created called `Role`.

```kotlin
enum class Role {
    STUDENT, LECTURER, ADMIN
}
```

The value from `Role` enum is used inside `Student` class.

```kotlin
// 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")
    }

}
```

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](https://kotlinlang.org/docs/classes.html).

- Learn more about data class in this [link](https://kotlinlang.org/docs/data-classes.html#data-classes-and-destructuring-declarations).

- Learn more about `object` in this [link](https://kotlinlang.org/docs/object-declarations.html).

- Learn more about generic in Kotlin in this [link](https://kotlinlang.org/docs/generics.html).

- Learn more about enum in this [link](https://kotlinlang.org/docs/enum-classes.html).

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.