← Back to Scala Course | Chapter 7: OOP Basics | Lesson 4 of 7

Access Modifiers

Access modifiers decide who can use something, like rooms with different locks. Things are open to everyone unless you mark them private or protected.

In this page:

  1. Access Modifiers
Syntax
scala
class ClassName {
  private var hidden: Type = value
  protected var inherited: Type = value
  var visible: Type = value
}

Access Modifiers

Scala members are public by default unless marked private (visible only within the class) or protected (visible within the class and its subclasses).

private[this] restricts access even further, to only the specific instance, not just the class. Encapsulating internal state as private and exposing it through public methods is standard OOP practice, same as in most other languages.

Note: Scala members are public by default -- unlike some languages where you must explicitly opt into public visibility.

Example: Access Modifiers

markup
class Account(startingBalance: Double) {
  private var balance = startingBalance

  def deposit(amount: Double): Unit = {
    balance += amount
  }

  def getBalance(): Double = balance
}

object Main extends App {
  val acc = new Account(100)
  acc.deposit(50)
  println(acc.getBalance())
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to access a private member from outside the class, such as acct.balance, which gives a compile error.
  2. Assuming private hides members from a companion object, when a companion object can access the class's private members.
  3. Making everything public by leaving out modifiers, exposing fields that should only change through methods like deposit.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.