What are the differences between private and protected visibility modifiers in Kotlin?

Viewed 2549

I just started to learn the kotlin and got confused with the protected access modifier my doubt is what is the exact differences between private and protected access modifier in kotlin. I have searched on the google but didn't get any satisfactory answer.

5 Answers

As in most OOP languages there are several modifiers in Kotlin:

public - class, function or property can be reached from anywhere in the project. In Kotlin by default the class, property or function are public

protected - class, function or property can be reached only by the current class subclasses

private - class, function or property can be reached only in the current class

internal - class, function or property can be reached from anywhere in the current module

As official documentatin says:

private means visible inside this class only (including all its members);

protected — same as private + visible in subclasses too;

From Kotlin doc:

private — means visible inside this class only (including all its members);

protected — same as private + visible in subclasses too;

By visible, it means the field or method can be accessed or used.

Check this for detailed description.

If you want to understand the protected concept you need a basic understanding of subclasses and inheritance.

Variables or Functions with protected access specifier can be seen from child classes. But private will binds the scope within the class.

consider this basic code:



    open class Outer {
        private val a = 1 // visible only for instance of class Outer
        protected open val b = 2 // visible for instance of Outer and another subclass which inherits Outer.
        val d = 4  // public by default
        protected class Nested {
            public val e: Int = 5
        }
    }

    public class Subclass : Outer() {
        // a is not visible
        // b, d are visible
        // Nested and e are visible

        override val b = 5   // 'b' is protected
    }


Note: The above code is from docs.

As it relates to class members:

  • items marked protected are visible within the class and subclasses
  • items marked private are visible within the class

As it relates to top-level declarations:

  • (protected is not applicable)
  • items marked private are visible within the same file
Related