Article image Classes and Objects

8. Classes and Objects

Page 8 | Listen in audio

In Kotlin, classes and objects are fundamental building blocks for creating well-structured and maintainable Android applications. Understanding how to effectively use these constructs will help you design robust and scalable applications. This section delves deep into the intricacies of classes and objects in Kotlin, exploring their features, capabilities, and best practices.

Classes in Kotlin

A class in Kotlin is a blueprint for creating objects. It encapsulates data and behavior, allowing you to define the properties and functions that an object will have. Kotlin classes are concise and expressive, making them ideal for Android development.

Defining a Class

To define a class in Kotlin, use the class keyword followed by the class name. Here's an example of a simple class:


        class Person {
            var name: String = ""
            var age: Int = 0
        }
    

In this example, the Person class has two properties: name and age. These properties are mutable, as indicated by the var keyword.

Constructors

Kotlin provides a primary constructor that can be declared directly in the class header. Here's how you can define a primary constructor:


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

In this version, the name property is read-only (immutable) because it uses val, while age remains mutable.

Initializing Properties

Kotlin allows you to initialize properties directly in the class body or in the constructor. Here's an example:


        class Person(val name: String, var age: Int) {
            var isAdult: Boolean = age >= 18
        }
    

The isAdult property is initialized based on the age property.

Secondary Constructors

While primary constructors are common, Kotlin also supports secondary constructors. They are defined using the constructor keyword:


        class Person {
            var name: String
            var age: Int

            constructor(name: String) {
                this.name = name
                this.age = 0
            }

            constructor(name: String, age: Int) {
                this.name = name
                this.age = age
            }
        }
    

Secondary constructors are useful when you need multiple ways to initialize a class.

Objects in Kotlin

An object in Kotlin is an instance of a class. It represents a specific realization of the class blueprint with actual values for its properties.

Creating Objects

To create an object, use the val or var keyword followed by the object name and the class constructor:


        val john = Person("John", 25)
    

This creates an object john of the Person class with the specified property values.

Accessing Properties and Methods

You can access the properties and methods of an object using the dot notation:


        println(john.name) // Outputs: John
        john.age = 26
        println(john.age) // Outputs: 26
    

This demonstrates how to read and modify the properties of an object.

Companion Objects

Kotlin introduces the concept of companion objects, which allow you to define static members in a class. Companion objects are declared using the companion object keyword:


        class Person {
            companion object {
                fun createAdult(name: String): Person {
                    return Person(name, 18)
                }
            }
        }
    

You can access the members of a companion object using the class name:


        val adult = Person.createAdult("Alice")
    

Companion objects are useful for factory methods and static utilities.

Inheritance

Kotlin supports inheritance, allowing you to create a new class based on an existing class. Use the open keyword to make a class inheritable, and the : symbol to inherit from a class:


        open class Animal {
            open fun sound() {
                println("Animal sound")
            }
        }

        class Dog : Animal() {
            override fun sound() {
                println("Bark")
            }
        }
    

The Dog class inherits from Animal and overrides the sound method.

Data Classes

Data classes in Kotlin are special classes that are intended to hold data. They automatically provide implementations for common methods like equals(), hashCode(), and toString():


        data class User(val name: String, val age: Int)
    

Data classes are perfect for representing simple data structures.

Sealed Classes

Sealed classes are used to represent restricted class hierarchies. They allow you to define a closed set of subclasses, which is useful for representing state or type hierarchies:


        sealed class Result {
            class Success(val data: String) : Result()
            class Error(val error: String) : Result()
        }
    

Sealed classes are particularly useful in scenarios like handling API responses.

Conclusion

Classes and objects are essential components of Kotlin programming for Android app development. Mastering these concepts enables you to create efficient, reusable, and maintainable code. Whether you're defining simple data structures with data classes or managing complex state hierarchies with sealed classes, Kotlin's class and object system provides the flexibility and power needed for modern Android development.

Now answer the exercise about the content:

What is the purpose of a companion object in a Kotlin class?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Inheritance in Kotlin

Next page of the Free Ebook:

9Inheritance in Kotlin

8 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text