The protected modifier

Kotlin provides another modifier, which is less restrictive as compared to the private modifier but very important when it comes to class hierarchy. This is called the protected modifier. Class properties and functions that are declared protected are accessible only in child classes. Take a look at the following example.

Create class A with two properties, i with protected visibility and j with public visibility. Create a child, class B, and inherit it with class A. Create a display function in class B and print all properties of class A  in it:

class A {
protected val i = 1
public val j = 2
}

open class
B : A() {
fun display(){
println("Protected i $i" )
println("Public j $j")
}
}

fun main(args: Array<String>) {
val b = B()
b.display()
}

All public and protected properties can be displayed without any problem. Let's create class C, create an instance of class A inside class C, and access all properties of class A in it:

class C {
val obj = A()
fun display(){
// println("Protected i ${obj.i}" )
println("Public j ${obj.j}")
}
}

Only the j property with the public modifier is available, and if we will try to access the protected modifier, Kotlin will throw the following error because protected members are accessible only in subclasses, not outside the class hierarchy:

Kotlin: Cannot access 'i': it is protected in 'A'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225