I have code with companion object and defined constructor as 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)
}
}
My question is why another object in same package also have access to this private constructor. I added private[this] so others didn't have access to it but nor companion had. Can I have private properties for class and companion object only ?
This code does not compile. Both Employee and Worker try to access the private constructor, and are rightfully denied access.
Your question speaks of a private variable, but there's no variable declared private.
So either your example is incomplete, or it is incorrect. Please correct the example so we can answer the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With