Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
class Animal {
func speak() { print("animal") }
}
class Dog: Animal {
override func speak() {
print("dog")
super.speak()
}
}
let pet: Animal = Dog()
pet.speak()dog animal
- Expecting
animal: thinking the declared typeAnimaldecides whichspeak()runs. The instance is aDog, so its overriding version runs. - Expecting
animal dog: thinking the parent's version always runs first.super.speak()runs exactly where the overriding method calls it.
- What would the program print without the
super.speak()line? - What changes if the
speak()method ofAnimalis markedfinal?