Kotlin Access Modifiers
20. Kotlin Access Modifiers
20.1 Public Access Specifier
20.2 Protected Access Specifier
20.3 Private Access Specifier
There are the three access specifiers in Kotlin: Public, Protected & Private. These access specifiers can apply on both properties and methods. If no access specifiers is written then by default it will be public.
Public Access Specifier
Public properties and methods can be accessed inside and outside of the class.
Example
open class Account{
public fun withdraw(i: Int) {
println("Withdrawal amount is $i")
}
}
fun main(args : Array<String>) {
var acc = Account()
acc.withdraw(10000)
}
Output
Withdrawal amount is 10000
In the above example, withdraw method is specified by public keyword that is accessed in main method.
Protected Access Specifier
Protected access specifier is generally used with inheritance. The properties and methods declared as protected can be accessed within the class and the inheriting class or child class.
Example
open class Account{
protected val name = "Smith"
}
class Holder:Account(){
fun name() : String
{
return name
}
}
fun main(args : Array<String>) {
var acc = Holder()
var name = acc.name()
print("Holder name is $name.")
}
Output
Holder name is Smith.
In the above example, name property is specified by the protected keyword that we can access in the inheriting class Holder.
Private Access Specifier
The private access specifier is available within the class only. This is used to hide the properties and methods to the outside of the class. A child class does not know parents private properties and methods.
Example
class Account{
private val name = "Smith"
}
class Holder:Account(){ // error
fun name() : String
{
return name
}
}
fun main(args : Array<String>) {
var acc = Holder()
var name = acc.name()
print("Holder name is $name.")
}
Output
Error:(4, 14) Kotlin: This type is final, so it cannot be inherited from
Error:(7, 16) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
invisible_fake final val name: String defined in Holder