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 trialThomas Dobson
7,511 PointsInheritance Code Challenge
Hello,
I managed to complete this Code Challenge but I couldn't help but feel like I cheated to some extent. I feel that I should have incorporated some sort of
override func {}
as it was the topic of the last lesson. I pushed a new constant doctorPreFix to the instance in place of first name, which in turn overrode the inherited interpolation function.
Did I go about this challenge correctly? Obviously there is more than one way to solve a problem but I am curious to know if my methodology differs from the intended solution. If it does; are there any drawbacks to my method of solving the challenge?
//Final Inheritance Code Challenge
class Person {
var firstName: String
let lastName: String
init(firstName: String, lastName: String)
{
self.firstName = firstName
self.lastName = lastName
}
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
// Enter your code below
class Doctor: Person
{
let doctorPreFix = "Dr."
override init(firstName: String, lastName: String) {
super.init(firstName: doctorPreFix, lastName: lastName)
}
}
let someDoctor = Doctor(firstName: "Jim", lastName: "Bean")
1 Answer
Jeff McDivitt
23,970 PointsHi Thomas - You are completely correct as you did not override the function, but you override the initialization which is ok but the code challenge could be completed much easier by just overriding the function. Also you do not need to create the prefix Dr. just write that into the return statement when you override the function.
class Person {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
class Doctor: Person {
override func fullName() -> String {
return "Dr. \(lastName)"
}
}
let someDoctor = Doctor(firstName: "Jeff", lastName: "McDivitt")
let IamDoctor = someDoctor.fullName()
Thomas Dobson
7,511 PointsThomas Dobson
7,511 PointsGreat thank you! I don't know why I I reinitialized in the subclass. Sill don't quite have my head around this yet.