Kotlin - Access Modifiers

Access Modifiers tells the scope of classes,objects,properties Kotlin supports public, private, protected, internal access modifiers.

Modifier Description
public Accessable everywhere
private Accessible inside the file containing the declaration
internal Accessible inside the same module (a set of Kotlin files compiled together)
protected Accessible inside Subclasses

By default access modifier is public


open class Parent() {
    var a = 1                 // public by default
    private var b = 2         // private to Parent class
    protected open val c = 3  // visible to the Parent and the Derived class
    internal val d = 4        // visible inside the same module

    protected fun e() { }     // visible to the Parent and the Derived class

class Derived: Parent() {

    // a, c, d, and e() of the Parent class are visible
    // b is not visible

    override val c = 9        // c is protected

fun main(args: Array) {
    val base = Parent()

    // base.a and base.d are visible
    // base.b, base.c and base.e() are not visible

    val derived = Derived()
    // derived.c is not visible

private modifier for Constructor

class Parent(val a: Int) {
    // code

This is default constructor, if we want to it private then we need to use contructor key word

class Parent private constructor(val a: Int) {
    // code

Subscribe For Daily Updates