WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Scala - Access Modifiers


This chapter takes you through the Scala access modifiers. Members of packages, classes or objects can be labeled with the access modifiers private and protected

You can apply accessibly to classes, traits, data members, member methods and constructors etc.

Scala provides only three types of access modifiers, which are given below:

  • No modifier
  • Protected
  • Private

Private Members

private access modifier is used to make data accessible only within class in which it is declared.

A private member is visible only inside the class or object that contains the member definition.

    class AccessExample{  
         private var a:Int = 5
         def show(){  
             println(a)  
         }  
    }  
    object MainObject{  
        def main(args:Array[String]){  
            var p = new AccessExample()  
            p.a = 7  
            p.show()  
        }  
    }  
Output error: variable a in class AccessExample cannot be accessed in AccessExample p.a = 7 ^ one error found

Protected Members

A protected member is only accessible from subclasses of the class and companion object Data members declared as protected are inherited in subclass.
    class AccessExample{  
         protected var a:Int = 5 
    }  
    class SubClass extends AccessExample{  
        def display(){  
            println("a = "+a)  
        }  
    }  
    object MainObject{  
        def main(args:Array[String]){  
            var s = new SubClass()  
            s.display()  
        }  
    }  
OUTPUT a = 5

Scala Example: No-Access-Modifier

In scala, when you don't mention any access modifier, it is treated as no-access-modifier. It is same as public in java.

    class AccessExample{  
         var a:Int = 5 
         def show(){  
             println(" a = "+a)  
         }  
    }  
      
    object MainObject{  
        def main(args:Array[String]){  
            var a = new AccessExample()  
            a.show()  
        }  
    }  
Output a = 5