Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdam Teale
10,989 Pointscalling function on type casted instance
Hey guys
I'm hoping that someone might be able to clear this up for me. I have one base class and two superclasses. I create an array that holds an instance of the base class and two instances of the superclasses. When I iterate this array I understood that each instance would be treated as the Base class (Animal). So why is it that in the for loop that each instance's "printName" function is called and not the Base "printName" function?
class Animal {
var name: String
init(_ name: String){s
self.name = name
}
func printName(){
print("Animal: \(self.name)")
}
}
class Dog: Animal{
override init(_ name: String){
super.init(name)
}
override func printName(){
print("Dog: \(self.name)")
}
}
class Cat: Animal{
override init(_ name: String){
super.init(name)
}
override func printName(){
print("Cat: \(self.name)")
}
}
let k = Dog("k")
let j = Cat("j")
let a = Animal("a")
var animals = [k, j, a]
for p in animals{
if let k = (p as? Animal) {
p.printName()
}
}
The printed output I get is:
Dog: k Cat: j Animal: a
I was expecting to see:
Animal: k Animal: j Animal: a
1 Answer
JLN CRML
30,362 PointsWhenever you override a method, the compiler will always execute the derived method. It has no access to the base class function, unless you call super. The array is indeed of type animal, but this is just to satisfy the compiler, in memory it may contain different instances of subclasses. An instance of a dog is basically a dog and an animal at the same time. For more information, I would recommend you looking up polymorphism.
JLN CRML
30,362 PointsJLN CRML
30,362 PointsOne thing I should add is that you are not printing the casted instance in your code.