Why does subclass create a copy of field when inheriting using a primary constructor?
For example
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?
}
}
As you can see, dog.toString()
returns "Billy" instead of "dog: Billy", does it mean this.name
is different from inherited name
? If so, then why does dog.name
return "dog: Billy" ?