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

Access Modifiers

In this page:

  1. Access Modifiers

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())
}
🔒

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.