为什么子类在使用主构造函数继承时会创建字段的副本?
例如
object Question
{
class Animal(var name : String) {
def setName(name : String) {
this.name = name
}
}
class Dog(name : String) extends Animal(name) {
this.setName("dog: " + name)
override def toString: String = this.name // this actually returns "Billy"
}
def main(args: Array[String]) {
val dog = new Dog("Billy")
println(dog.toString) // output "Billy", why?
println(dog.name) // output "dog: Billy", why?
}
}
正如你所看到的,dog.toString()
返回“Billy”而不是“dog: Billy”,这是否意味着this.name
与继承的名称
?如果是这样,那么为什么 dog.name
返回“dog: Billy”?
最佳答案
如果您使用 -Xlint
选项运行编译器,您应该会看到以下内容。
warning: private[this] value name in class Dog shadows mutable name inherited from class Animal. Changes to name will not be visible within class Dog - you may want to give them distinct names.
如果将 name
参数重命名为 Dog
类,警告就会消失,并且输出会更加一致,并且可能更接近预期。
关于scala - 为什么 Scala 子类在使用主构造函数继承时会创建字段的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34457583/