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

David Lallone
David Lallone
6,020 Points

Why can I implement square in NewtonCalculator?

class Calculator {

    class func squareRoot(value: Double) -> Double {
        return sqrt(value)
    }

    final class func square(value: Double) -> Double {
        return value * value
    }

}

class NewtonCalculator : Calculator {

    override class func squareRoot(value: Double) -> Double {
        var guess = 1.0
        var newGuess: Double

        while true{
            newGuess = (value/guess + guess)/2
            if(guess == newGuess){
                return guess
            }

            guess = newGuess
        }
    }
    //Why does this function work here when its marked as "final" up above?
    class func square()->Double{
        return 5+5
    }
}

As commented in code above, why does this work? In the video he says that I shouldn't be able to implement another square method.

2 Answers

Michael Hulet
Michael Hulet
47,912 Points

It works because you're not overriding the same method that's on Calculator. The names of the methods are different, and they take different types in their arguments, so they're fundamentally different. Here's an example:

//For the sake of brevity, I'm using Swift's special header syntax
class Calculator{
    final class func square(value: Double) -> Double
}

class NewtonCalculator: Calculator{
    class func square() -> Double //This is legal, because it takes no parameters, but the superclass's takes a Double
    class func square(value: Int) -> Double //This is legal, because it takes an Int, but the superclass's takes a Double
    class func square(root: Double) -> Double //This is legal, because its name is square(root:), and the superclass's is square(value:)
    class func square(value: Double) -> Int //This is legal, because it returns an Int, but the superclass's returns a Double
    override class func square(value: Double) -> Double //This is illegal, because it's named the same, takes the same types of parameters, and returns the same type as the superclass, and it attempts to override the superclass's implementation, but the superclass's implementation is marked final
}
David Lallone
David Lallone
6,020 Points

Thank you for the response. I probably should have known that based of what I've learned so far. Anyhow, I now know why. Thanks