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 Intermediate Swift 2 Value Semantics, Type Methods and Inheritance Final Classes

Laura Nieuwenhuis
Laura Nieuwenhuis
2,356 Points

How come the compiler can’t know which squareRoot() method we’re calling?

In the video it is said that when we’re calling the squareRoot() method, the compiler doesn’t know which specific method we’re calling. I don’t understand that. It is plainly obvious we would be calling the one from the subclass since we’re also calling it on the subclass, right? How come the compiler can’t figure this out?

2 Answers

Jakub Duchniewicz
Jakub Duchniewicz
3,176 Points

Hey, Subclass inherits methods from its superclass, so when you call a squareRoot() method on a subclass, the compiler doesn't know which squareRoot() method it should call.

Hope I was of any help to you, Cheers

Laura Nieuwenhuis
Laura Nieuwenhuis
2,356 Points

I'm sorry, but no it doesn't help. You see my point is that I don't understand why the compiler doesn't know which squareRoot() method it should call. It should know. It's plainly obvious when you read the code. There's nothing dynamic here as far as I can tell.

There's simply a class with a class-method and a subclass that overrides that class-method and then the guys calls the class-method ON THE SUBCLASS. How can the compiler not know that that means it should call the class-method on the subclass?

Do you understand what I'm trying to say?

Hi Laura,

I agree with you, this seems a bit inaccurate or at least confusing :)

Here's my take on it.

Note that the instructor continues to say "... it's only determined at runtime when the compiler knows that we are either using the superclass or it's subclass".

In the example, the compiler knows which method we are calling because we call the method by using dot annotation on the class. You can visualize this by by clicking on the .squareRoot method and Xcode will show you the method in the corresponding class, i.e. both will be marked with dotted underline.

So it seems a bit inaccurate to say "The compiler does not know which specific method we are calling".

I think what the instructor means is that it's not evaluated at compile-time, but at runtime, and that's when the program decides which implementation to execute.