Sobes.tech
Junior

Tell me about access modifiers in Java and Kotlin.

sobes.tech AI

Answer from AI

In Java:

  • public: accessible from anywhere.
  • protected: accessible within the class, package, and subclasses.
  • (no modifier): accessible within the package (package-private).
  • private: accessible only within the class.

In Kotlin:

  • public: accessible from anywhere (default).
  • internal: accessible within the module.
  • protected: accessible within the class and its subclasses (differs from Java in terms of package access).
  • private: accessible only within the class/file.

Differences:

  • Kotlin does not have a "package-private" modifier; its analogue is internal with a different scope (module).
  • In Kotlin, protected does not provide package-level access as in Java.
  • In Kotlin, private can also be used for top-level declarations (functions, properties) in a file, making them accessible only within that file.
// Example in Kotlin
package com.example.myapp

private const val API_KEY = "secret" // Visible only in this file

class MyClass {
    private val internalState = 1 // Visible only within MyClass
    protected fun protectedMethod() {} // Visible in MyClass and its subclasses
    internal fun internalMethod() {} // Visible within the module
}