Access Modifiers
In this page:
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
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())
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: