Sling Academy
Home/Kotlin/Using Private, Protected, and Public Modifiers in Kotlin

Using Private, Protected, and Public Modifiers in Kotlin

Last updated: November 30, 2024

In Kotlin, access modifiers are used to set the visible scope of classes, objects, interfaces, constructors, functions, properties, and their setters. Understanding how these modifiers work can help you design your software architecture effectively while maintaining encapsulation and security.

Public Modifier

The public modifier is the default visibility and is accessible from anywhere in the application. When a class, function, or property is declared as public, it becomes available to any code that can access the location where the declaration itself is visible.

// Public by default
class PublicClass {
    fun publicFunction() {
        println("This function is public")
    }
}

fun main() {
    val instance = PublicClass()
    instance.publicFunction()  // Accessible from anywhere
}

Private Modifier

The private modifier restricts the visibility to the file where it is declared. A class, object, interface, or function marked as private can't be accessed from outside that particular file.

private class PrivateClass {
    private fun privateFunction() {
        println("This function is private")
    }

    fun callPrivateFunction() {
        privateFunction()  // Accessible within the class
    }
}

fun main() {
    val instance = PrivateClass()  
    // instance.privateFunction()  // This line would cause an error
    instance.callPrivateFunction() // This works fine
}

Protected Modifier

The protected modifier is more restricted and can be used within a class and its subclasses. However, unlike Java, you cannot declare top-level definitions (like functions, properties) with protected visibility in Kotlin outside a class or object.

open class SuperClass {
    protected fun protectedFunction() {
        println("This function is protected")
    }
}

class SubClass : SuperClass() {
    fun accessProtectedFunction() {
        protectedFunction()  // Accessible function from subclass
    }
}

fun main() {
    val instance = SubClass()
    instance.accessProtectedFunction()
    // instance.protectedFunction()  // This line would cause an error
}

Practical Use-Cases

Using the correct visibility modifiers is crucial for maintaining a modular codebase:

  • Public: When you intend for certain classes or functions to be a part of the core interface of your module or application.
  • Private: Useful for implementation details that are not necessary for the users of the module to see or use.
  • Protected: Ideal for scenarios where some functionality needs to be extended but hidden from other parts of the application.

In conclusion, understanding these access modifiers and using them appropriately allows you to create concise, readable, and well-encapsulated Kotlin code. Make sure you choose the right modifier for the right scenario to adhere to good coding practices and data integrity.

Next Article: How to Define Properties in Kotlin Classes

Previous Article: Understanding Encapsulation in Object-Oriented Programming in Kotlin

Series: Kotlin Object-Oriented Programming

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin