Techoceanhub logo

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

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .