Kotlin inheritance and visibility modifiers

There are four visibility modifiers in Kotlin: private, protected, internal and public. The default visibility public is used if there is no explicit modifier.

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

protected: same as private + visible in subclasses too

internal:any client inside this module who sees the declaring class sees its internal members

public: any client who sees the declaring class sees its public members.

The keyword open allows a class or a property to be inherited and overridden.

// open means the class can be inherited
open class Vehicle(open var name: String) {
    private val typeCode = 1
    protected open val weight = 5000
    internal val width = 2
    val height = 4  // public by default
}

// inheriting from Vehicle
class Car(override var name: String) : Vehicle(name) {
    // typeCode is not visible
    // weight, width and height are visible

    override val weight = 3000   // 'weight' is protected

    fun getWeightVal(): Int {
        return weight
    }
}


fun main(args: Array<String>) {
    var car = Car("Flash")

    println("name = ${car.name}, weight=${car.getWeightVal()}, width=${car.width}, height=${car.height}")
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search