Consider the following Kotlin code snippet. What will be printed when Main().test() is called?
open class Main { private val secret = "hidden" internal val internalInfo = "inside module" protected val protectedInfo = "protected data" val publicInfo = "visible everywhere" fun test() { println(secret) println(internalInfo) println(publicInfo) } } fun main() { Main().test() }
Remember that private members are accessible inside the same class, internal inside the same module, and protected only in subclasses.
The test() function is inside the Main class, so it can access private, internal, and public members. The protected member is not accessed here. So the output prints secret, internalInfo, and publicInfo values.
What happens if you try to access a private property from outside its class in Kotlin?
class Box { private val secret = "top secret" } fun main() { val box = Box() println(box.secret) }
Think about what private means in Kotlin.
In Kotlin, private means the property is only accessible inside the class it is declared in. Trying to access it outside causes a compile-time error.
Examine the code below. Why does it fail to compile?
open class Parent { protected val data = "parent data" } class Child : Parent() { fun printData() { println(data) } } fun main() { val child = Child() println(child.data) }
Remember where protected members can be accessed from.
The data property is protected, so it can be accessed inside Child class methods, but not from outside. The line println(child.data) is outside the class, causing a compile error.
Assume ModuleA defines this class:
class Example {
internal val info = "module info"
val publicInfo = "public info"
}And ModuleB tries to run:
fun main() {
val ex = Example()
println(ex.info)
println(ex.publicInfo)
}What happens?
Think about what internal means across modules.
internal means visible only inside the same module. Accessing info from another module causes a compile error. publicInfo is accessible everywhere.
Choose the visibility modifier that fits this description:
- Accessible inside the class and subclasses
- Not accessible from unrelated classes in the same module
Think about which modifier restricts access to subclasses only.
protected allows access inside the class and subclasses regardless of module. internal allows access anywhere in the module but not outside. private restricts to the class only. public is everywhere.