T E C h O C E A N H U B

Different modifiers in Kotlin (Chapter-14)

let us study different modifiers in kotlin, they are listed as private, protected, internal, and public. By default visibility modifier is public. If you do not specify any visibility modifier, public is used by default, which means that your declarations will be visible everywhere.

Let us see a simple example of different modifiers:-

// file name: sample.kt
private fun add() { ... } // visible inside sample.kt but not visible outside
public var num1: Int = 5 // visible everywhere
internal val num1 = 6    // visible inside the same module

The above internal modifier seems to be confusing but it simply states “The internal visibility modifier means that the member is visible within the same module. If we go into detail, a module is a set of Kotlin files compiled together“.

We have not seen a protected modifier. let us see a simple example of a protected modifier.

// base class
open class Fruits {
   open protected val int = 10 // protected variable
}
// derived class
class Apple: Fruits() {
    fun getMethod(): Int {
        return int         // accessed from the subclass
    }
}
fun main(args: Array<String>) {
    var obj = Apple()
    println("The value of integer is: "+obj.getvalue())
}

The protected modifier in Kotlin means that it is strictly accessible only by the declaring class and subclasses, and We need to mark the protected variable or function using open keyword to override in the derived class otherwise variable declared in the base class as protected cannot be overridden.

Feel free to read the post and comment below.

Below is my android application, and is useful for people who has Google Opinion Rewards to cash out. https://play.google.com/store/apps/details?id=com.manasvi.sawant.rewardtocash

If you wanted to create a website, please visit my Fiverr gig link below or contact me at support@techoceanhub.com. https://www.fiverr.com/share/EdZ9L7

Copyright ©TechOceanhub All Rights Reserved.