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 trial

iOS Object-Oriented Swift 2.0 Class Inheritance Overriding Methods

Johann Peters
Johann Peters
40,749 Points

inheritance getFullName() ?

What's wrong?

class Person { let firstName: String let lastName: String

init(firstName: String, lastName: String) {
    self.firstName = firstName
    self.lastName = lastName
}

func getFullName() -> String {
    return "\(firstName) \(lastName)"
}

} // Enter your code below class Doctor: Person{

override init(firstName: String, lastName: String) {
    super.init(lastName: lastName)
    self.lastName = lastName

} override func getFullName() -> String{ return "Dr. (lastName)" }

} let someDoctor = Doctor.getFullName("Johnson")

classes.swift
class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }

    func getFullName() -> String {
        return "\(firstName) \(lastName)"
    }
}
// Enter your code below
class Doctor: Person{

    override init(firstName: String, lastName: String) {
        super.init(lastName: lastName)
        self.lastName = lastName
}
    override func getFullName() -> String{
        return "Dr. \(lastName)"
    }

}
let someDoctor = Doctor.getFullName("Johnson")

1 Answer

Hi Johann,

A couple of issues in your code there - nothing serious so you're on the right track.

Firstly, there's no need to override the initializer. That is fine as it is. The Doctor instance will still have a first and last name, same as a Person.

Your getFullName() is perfect - and that is all that is needed in the Doctor class.

Lastly, you didn't create the instance correctly. You need to create the instance someDoctor then use that instance to try the `getFullName() method. All that looks like:

// Enter your code below
class Doctor: Person {
    override func getFullName() -> String {
        return "Dr. \(lastName)"
    }
}

let someDoctor = Doctor(firstName: "Steve", lastName: "Smith")
someDoctor.getFullName()

I hope that makes sense!

Steve.

Johann Peters
Johann Peters
40,749 Points

Thanks Steve! Good explanation!

Glad it helped out!

Steve.