Scala – Access Modifiers

  • date 28th April, 2021 |
  • by Prwatech |
  • 0 Comments

The basics of Scala access modifiers

 

Access Modifiers in scala are utilized to characterize the access field of members of packages, classes or objects in scala. For utilizing an access modifier, you should remember its keyword for the definition of package, class or object. These modifiers will restrict access to the members to the specific part of code.

Scala access modifiers control the visibility and accessibility of classes, traits, methods, and fields within a Scala program. There are three primary access modifiers in Scala:

  1. Private: Members marked as private are accessible only within the enclosing scope, such as a class or object. Private members cannot be accessed from outside the enclosing scope, even by subclasses.

  2. Protected: Members marked as protected are accessible within the defining class and its subclasses. Protected members can be accessed by subclasses but not by other classes in the same package.

  3. Public (No Modifier): Members without explicit access modifiers are public by default. Public members are accessible from anywhere within the same package or from external packages.

Additionally, Scala supports package-level access modifiers (private[package] and protected[package]) that restrict visibility to specific packages.

Types of Access Modifiers

Private members

Protected members

Public members

Use case 1:

Private Members in Scala

class Prwatech {
private var a:Int=7
def show(){
a=6
println(a)
}
}
object access extends App{
var e=new Prwatech()
e.show()

}

output:

6

Use case 2:

Protected members in scala

class prwatech {
protected var a:Int=7
def show(){
a=8
println(a)
}
}
class prwatech1 extends prwatech{
def show1(){
a=9
println(a)
}
}
object access extends App{
var e=new prwatech()
e.show()
var e1=new prwatech1()
e1.show1()
//e.a=10
//println(e.a)
}

output:

8

9

Use case 3:

Public members in scala

class Example {
var a:Int=10
}
object access extends App{
var e=new Example()
e.a=5
println(e.a)
}

output:

5

Quick Support

image image