gpt4 book ai didi

Scala 私有(private)访问修饰符范围

转载 作者:行者123 更新时间:2023-12-03 04:44:39 25 4
gpt4 key购买 nike

我有带有伴生对象的代码,并将构造函数定义为私有(private):

class Person private[Person] (var age: Int, var name: String) {
private[Person] def this(name: String) = this(0, name)
}

private class Employee(age: Int, name: String) extends Person(age, name)

private class Worker(age: Int, name: String) extends Person(age, name)

object Person {
def prettyPrint(p: Person) = println("name:%s age:%s".format(p.name, p.age))
def apply(age: Int, name: String) = new Person(age, name)
def apply() = new Person(0, "undefined")
def apply(age: Int, name: String, personType: String): Person = {
if (personType == "worker") new Worker(age, name)
else if (personType == "employee") new Employee(age, name)
else new Person(age, name)
}

}

我的问题是为什么同一包中的另一个对象也可以访问这个私有(private)构造函数。我添加了私有(private)[this],这样其他人就无法访问它,但同伴也无法访问它。我可以仅拥有类和伴生对象的私有(private)属性吗?

最佳答案

该代码无法编译。 EmployeeWorker 都尝试访问私有(private)构造函数,并且理所当然地被拒绝访问。

您的问题涉及私有(private)变量,但没有声明为私有(private)的变量。

因此,您的示例要么不完整,要么不正确。请更正示例,以便我们回答问题。

关于Scala 私有(private)访问修饰符范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10211720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com