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 访问修饰符