Home » Scala language

Access modifiers in Scala

Access modifiers in Scala: In this tutorial, we are going to learn about the various access modifiers in Scala programming language.
Submitted by Shivang Yadav, on June 17, 2019

Access modifiers are used in order to restrict the usage of a member function to a class or a package. Using access modifiers data hiding takes place which is a very important concept of OOPs.

The access to a class, object or a package can be restricted by the use of three types of access modifiers that are 1) public (accessible to everyone), 2) private (accessible only in the class), and 3) protected (accessible to class and its subclasses).

1) Public access modifier

It is the default type of modifier in Scala. In Scala, if you do not use any access modifier then the member is public. Public members can be accessed from anywhere.

Syntax:

    def function_name(){}
    or 
    public def fuction_name(){}

2) Private access modifier

In private access, access to the private member is provided only to other members of the class (block). It any call outside the class is treated as an error.

Syntax:

    private def function_name(){}

3) Protected access modifier

In protected access, the availability of the member function is limited to the same class and its subclass. Excess without inheritance is treated as an error.

Syntax:

    protected def function_name(){}

Scala example to demonstrate use of public, private and protected access modifiers

class school(rlno: Int , sname : String ,sch_no : Int) {
	//roll no can only be used by school or its subclasses
	protected  var rollno = rlno; 
	var name = sname;
	// this variable is only for the class
	private var scholar=sch_no; 
}
class seventh extends school {
	def dispaly(){
		// public and private member are used...
		print("Roll no of " + name + " is " + rollno) 
	}
}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.