Start Coding

Topics

Kotlin Classes

Classes are fundamental building blocks in Kotlin, providing a blueprint for creating objects. They encapsulate data and behavior, promoting code organization and reusability.

Class Declaration

In Kotlin, classes are declared using the class keyword. Here's a simple class declaration:

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

This creates a basic class named Person with two properties: name and age.

Constructors

Kotlin classes can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header:

class Person(val name: String, var age: Int) {
    // Class body
}

For more complex initialization logic, you can use an init block:

class Person(val name: String, var age: Int) {
    init {
        println("Person created: $name, $age years old")
    }
}

Properties and Methods

Classes can contain properties (variables) and methods (functions). Here's an example:

class Person(val name: String, var age: Int) {
    fun introduce() {
        println("Hi, I'm $name and I'm $age years old.")
    }
}

Creating Objects

To create an object from a class, you use the class name followed by parentheses:

val john = Person("John Doe", 30)
john.introduce() // Output: Hi, I'm John Doe and I'm 30 years old.

Visibility Modifiers

Kotlin provides visibility modifiers to control access to class members:

  • public (default): Visible everywhere
  • private: Visible inside the class only
  • protected: Visible in the class and its subclasses
  • internal: Visible inside the same module

Inheritance

Kotlin classes are final by default. To allow inheritance, use the open keyword:

open class Animal(val name: String) {
    open fun makeSound() {
        println("The animal makes a sound")
    }
}

class Dog(name: String) : Animal(name) {
    override fun makeSound() {
        println("The dog barks")
    }
}

For more advanced class features, explore Kotlin Inheritance and Kotlin Interfaces.

Best Practices

  • Keep classes focused on a single responsibility
  • Use meaningful names for classes and their members
  • Prefer composition over inheritance when possible
  • Use Kotlin Data Classes for simple data containers
  • Leverage Kotlin's concise syntax for cleaner class definitions

Classes form the backbone of object-oriented programming in Kotlin. They provide a powerful way to structure your code and model real-world entities in your programs.

To dive deeper into Kotlin's object-oriented features, check out Kotlin Objects and Kotlin Constructors.