scala 访问修饰符_Scala访问修饰符–私有,受保护的和公共的

scala 访问修饰符

The restriction of scope to certain places is realized with the help of access modifiers. public, private and protected are the three access modifiers used in Scala. Include the keywords private/protected/public in the definition of class, object or package to enforce the corresponding scope. If none of these keywords are used, then the access modifier is public by default.

通过访问修饰符可以实现将范围限制在某些地方。 publicprivateprotected是Scala中使用的三个访问修饰符。 在类,对象或包的定义中包括关键字private / protected / public,以强制执行相应的范围。 如果未使用这些关键字,则默认情况下,访问修饰符为public。

私人会员 (Private member)

Private members are available only inside the class or to the object containing the member definition. The private access modifier can be used for variables and methods as well. Consider an example to show the private members;

私有成员仅在类内部或包含成员定义的对象中可用。 private访问修饰符也可以用于变量和方法。 考虑一个显示私人成员的例子;

class Student {

class Student1 {

private var sage = 0
private def studage() {
println("Student Age is :"+sage)
}
}

class StudentAge {
sage = sage + 4
studage()
}

(new Student1).sage

(new Student1).studage()

}

Here we define an outer class Student and an inner class Student1 with variable “sage” which is a private member.

在这里,我们定义了一个外部类Student和一个内部类Student1,它们的变量“ sage”是一个私有成员。

In the StudentAge class we just access and add 4 to the sage(student age) variable. Now when we try accessing the variable sage from another object instantiated as “new Student1”, an access error is thrown as below.

在StudentAge类中,我们仅访问sage(学生年龄)变量并将其添加4。 现在,当我们尝试从实例化为“ new Student1”的另一个对象访问变量sage时,将引发如下访问错误。

In Student1 class we also have defined a private method studage() in which we are just printing the student age. We are then calling this method from within StudentAge class. This is allowed as the Student age class is the innermost nested class of Student1. studage method cannot be accesed from StudentAge class.

在Student1类中,我们还定义了一个私有方法studage(),其中我们只是在打印学生年龄。 然后,我们在StudentAge类中调用此方法。 这是允许的,因为Student年龄类是Student1的最内层嵌套类。 不能从StudentAge类访问studage方法。

Run the above example code to see the error message as shown below;

运行上面的示例代码以查看错误消息,如下所示;

error: variable sage in class Student1 cannot be accessed in Student.this.Student1

(new Student1).sage

error: method studage in class Student1 cannot be accessed in Student.this.Student1

(new Student1).studage()

Below image shows the complete code execution in Scala shell.

下图显示了Scala shell中完整的代码执行。

受保护的成员 (Protected Member)

Protected members can be accessed from subclasses of the class in which the member is defined (inherited class). This can also be used for methods as well as variables.

可以从定义成员的类的子类(继承的类)中访问受保护的成员。 这也可以用于方法和变量。

Consider an example shown below;

考虑下面的示例;

class Student {
protected var sid = 12
protected def studId() {
println("Student Id is :"+sid)
}
}

class CollegeStudent extends Student {
sid = sid + 6
studId()
}

class TestStudent {
(new Student).sid
(new Student).studId()
}

The class Student is created consisting of a variable sid and a method studId() in which we are printing the student id.

创建的Student类由变量sid和方法studId()组成,我们在其中打印学生ID。

Next, we are creating a class CollegeStudent extending the super class Student and incrementing the variable sid by 6 and then invoke the method studId().

接下来,我们将创建一个CollegeStudent类,该类将扩展超类Student,并将变量sid递增6,然后调用方法studId()。

We create another class TestStudent and try to the access the sid variable and then call studid() after creating a new object of the Student class. Since TestStudent is not a subclass of Student, an error is thrown as sid and studId() are not accessible. This is because they are specified as protected members and can only be accessed by subclassing the main class. Class CollegeStudent is a subclass of Student and hence can access sid variable and studId method.

我们创建另一个类TestStudent并尝试访问sid变量,然后在创建Student类的新对象后调用studid()。 由于TestStudent不是Student的子类,因此会抛出错误,因为sid和studId()无法访问。 这是因为它们被指定为受保护成员,并且只能通过对主类进行子类化来访问。 CollegeStudent类是Student的子类,因此可以访问sid变量和studId方法。

Run the above code to see the following error in output.

运行上面的代码以查看以下错误输出。

<console>:9: error: variable sid in class Student cannot be accessed in Student
 Access to protected method sid not permitted because
 enclosing class TestStudent is not a subclass of
 class Student where target is defined
       (new Student).sid
                     ^
<console>:10: error: method studId in class Student cannot be accessed in Student
 Access to protected method studId not permitted because
 enclosing class TestStudent is not a subclass of
 class Student where target is defined
       (new Student).studId()
                     ^

But when we try to run the program and access the variable and method from inside CollegeStudent class, there won’t be any errors.

但是,当我们尝试运行程序并从CollegeStudent类内部访问变量和方法时,不会出现任何错误。

公众成员 (Public member)

The default access modifier is public. When the keywords private or protected is not specified then the members are treated as public by the compiler and we don’t have to explicitly specify the keyword “public”.

默认访问修饰符是public。 当未指定关键字private或protected时,编译器会将成员视为public,而我们不必显式指定关键字“ public”。

Consider an example to depict the public members;

考虑一个描述公众成员的例子;

class Student {

class Stud {
var sname = "Adam"
def studName() {
println("Student name is :"+sname)
}

class TestStud {
studName()
}
}

(new Stud).sname

(new Stud).studName()
}

Student class is created with an inner class Stud along with variables sname and method studName which prints the student name.

使用内部类Stud以及变量sname和方法studName创建学生类,该变量显示学生名。

TestStud class is created calling the studName() method. Now when we try accessing the sname variable or invoke studName() outside the Stud class, it becomes accessible since attributes with access modifier public is visible to any of the classes.

创建TestStud类,调用studName()方法。 现在,当我们尝试访问sname变量或在Stud类之外调用studName()时,由于具有访问修饰符public的属性对于任何类都是可见的,因此它变得可访问。

When we execute the above code the Student class is created successfully without any errors.

当我们执行上述代码时,将成功创建Student类,而不会出现任何错误。

The following table depicts the accessibility of various access modifiers for class, package, subclass and all classes.

下表描述了类,包,子类和所有类的各种访问修饰符的可访问性。

ModifierClassPackageSubclassEvery class
publicYesYesYesYes
protectedYesNoYesNo
privateYesNoNoNo
修饰符 子类 每堂课
上市
受保护的 没有 没有
私人的 没有 没有 没有

保护范围 (Scope of Protection)

Access modifiers can be suffixed with qualifiers in the []. The modifiers of type protected[Y] or private[Y] specifies that access is provided upto Y where Y can be a package, class or singleton object.

访问修饰符可以在[]中带有修饰符后缀。 类型protected [Y]或private [Y]的修饰符指定提供访问权限,直到Y,其中Y可以是包,类或单例对象。

Consider an example to depict the usage of these qualifiers

考虑一个描述这些限定词用法的示例

package student {

package graduatestudent {

class Stud {
protected[graduatestudent] var degree = null
private[student] var marks = 60
private[this] var age = 0

def studdegree(stu:Stud) {
println(stu.degree)
println(stu.marks)
println(stu.age)
}
}
}
}

To type the above code in the shell we have to first enter the paste mode by typing :paste -raw and then insert this code. Once the code is inserted completely press ctrl-D to exit from the paste mode and run the code (enter key). In the normal mode an error is thrown as illegal start of definition after declaring the package.

要在外壳中键入上面的代码,我们必须首先通过键入:paste -raw进入粘贴模式,然后插入此代码。 完全插入代码后,按ctrl-D退出粘贴模式并运行代码(输入键)。 在正常模式下,声明程序包后,将以错误的错误开头定义开始。

Here we are declaring packages student and graduatestudent. We are defining a class Stud with the variable “degree” having protected access modifier qualified by the package name graduatestudent, variable marks of private access qualified to student package and age variable for the current instance of the Stud class. studdegree() method is defined in which we are trying to access the variables degree, marks and age. The variable age cannot be accessed and so it throws an error as below.

在这里,我们宣布学生和研究生套餐。 我们正在定义一个Stud类,其变量“学位”具有受保护的访问修饰符,该修饰符由软件包名称毕业生学生限定,私人访问的变量标记符合学生软件包的要求,并且为Stud类的当前实例具有年龄变量。 定义了studdegree()方法,我们尝试在其中访问变量度,标记和年龄。 变量age无法访问,因此引发如下错误。

value age is not a member of student.graduatestudent.Stud
println(stu.age)

Key points about the variables degree, marks and age

有关变量程度,标记和年龄的要点

  • The variable degree can be accessed by any class within the package graduatestudent

    研究生课程包中的任何班级都可以访问可变学位
  • The variable marks can be accesed by any class within the package student.

    软件包中的任何班级都可以访问可变标记。
  • The variable age can be accessed only on the implicit objects within instance methods(this).

    只能在实例方法(this)中的隐式对象上访问变量age。

That’s all for access modifiers in Scala, its very close to java access modifiers except the default modifier is public here. We will look more Scala core features in the coming posts.

这就是Scala中访问修饰符的全部内容,它与Java访问修饰符非常接近,除了默认修饰符在此处是公共的。 在接下来的文章中,我们将介绍更多Scala核心功能。

翻译自: https://www.journaldev.com/7584/scala-access-modifiers-private-protected-and-public

scala 访问修饰符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值