Here are some thoughts. You'll start to recognize these patterns later on in the course.
If you see redundant code, this is a sign to you that perhaps you can move the code to the parent class. Can you spot the redundant code here?
class Persian: Cat {
override func speak() {
print("MEEOWW")
}
// Compare to code in Lion class
override init(legs: Int, isTame: Bool) {
super.init(legs: legs, isTame: isTame)
}
}
class Lion: Cat {
override func speak() {
print("ROAR") // <-- Change the default behaviour. Excellent.
}
// Compare to code in Persian class
override init(legs: Int, isTame: Bool) {
super.init(legs: legs, isTame: isTame)
}
}
The same code is in two derived classes. Both are subclassed from Cat. So maybe this redundant code belongs in the Cat class, instead? But take a closer look. Maybe you're not really overriding anything here?
Indeed, you are just calling the super class' initializer and not making any changes. Let's mix it up.
Override a Superclass Method
So why might you want to override the Cat initializer? Well, Cat gives you the option to designate whether a cat is tame or not. Think about the use case: would you ever consider a Lion to be tame?
So consider the case where you instantiate a Lion object in your code as you did in your example above:
let sammy = Lion(legs: 4, isTame: false) // <-- Would you consider a lion tame by default?
sammy.speak()
// Consider instead
class Lion: Cat {
override func speak() {
print("ROAR") // <-- Change the default behavior
}
// Lions have specific properties that are different from domestic cats.
init(legs: Int ) {
super.init(legs: legs, isTame: false) // <-- Lions are never tame. Even captive lions!
}
}
let leoTheLion = Lion(legs: 4) // <-- initializer always sets isTame to false
Keep coding