As i understand vals are immutable in Scala. However in case of inheritance we can override a val defined in the base class. If the val member already got created when the base class was constructed then how can derived class override it? What am i missing?
class Animal ()
{
val talk: String = "Ha Ha!"
}
class Dog extends Animal
{
override val talk = "Woof Woof!"
}
class Cat extends Animal
@main def mainFn() = {
var happyAnimal = new Animal()
println(happyAnimal.talk)
happyAnimal = new Dog()
println(happyAnimal.talk)
happyAnimal = new Cat()
println(happyAnimal.talk)
}
Output
Ha Ha! Woof Woof! Ha Ha!