scala 訪問修飾符
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.
訪問修飾符用于將成員函數的使用限制為類或包。 使用訪問修飾符進行數據隱藏,這是OOP的非常重要的概念。
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)公共(所有人都可以訪問) , 2)私有(僅在類中可以訪問)和3)受保護(可以訪問)類及其子類) 。
1)公共訪問修飾符 (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.
它是Scala中默認的修飾符類型。 在Scala中,如果不使用任何訪問修飾符,則該成員是公共的。 可以從任何地方訪問公共成員。
Syntax:
句法:
def function_name(){}
or
public def fuction_name(){}
2)私人訪問修飾符 (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)受保護的訪問修飾符 (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示例演示使用公共,私有和受保護的訪問修飾符 (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)
}
}
翻譯自: https://www.includehelp.com/scala/access-modifiers-in-scala.aspx
scala 訪問修飾符