liveBook · Manning

Protected member

As explained in Kotlin in Action, 2E

The protected modifier restricts access to a declaration to its containing class and subclasses in Kotlin.

A protected member is visible inside its containing class and its subclasses, but not to unrelated callers or same-package code. Kotlin deliberately differs from Java here: package membership does not grant protected access. section 4.1.3

Subclass access, extension rejection

open class TalkativeButton { protected fun whisper() = println("Let's talk!") } class Child : TalkativeButton() { fun speak() = whisper() // allowed } fun TalkativeButton.giveSpeech() { whisper() // error: extensions gain no protected access } section 4.1.3

Table 4.2 Kotlin visibility modifiers (view table figure)

Modifier

Class member

Top-level declaration

public (default)

Visible everywhere

Visible everywhere

internal

Visible in a module

Visible in a module

protected

Visible in subclasses

—

private

Visible in a class

Visible in a file

Use the visibility table to compare protected with public, internal, and private declarations, including its absence for top-level declarations. section 4.1.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines the visibility rule, demonstrates an extension-function failure, and contrasts Kotlin with Java package behavior.
Examples
Uses TalkativeButton, its protected whisper function, a subclass call, and an extension-function access error.
What you can do after
Apply it via Kotlin visibility modifiers to expose implementation details to subclasses while blocking unrelated callers.
How it connects
Connects visibility modifiers with subclasses, extension functions, Java, and Java bytecode.

Also explained in

Compare how 4 books explain protected member →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.