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 Inheritance Overriding Methods

Hariidaran Tamilmaran
seal-mask
.a{fill-rule:evenodd;}techdegree
Hariidaran Tamilmaran
iOS Development Techdegree Student 19,305 Points

Concerning about D.R.Y.

Isn't Amit already repeating the discountedPrice() method for the Clothing class, when it is already present for the Product class?

And how is he is 'not' repeating himself, by typing super.discountedPrice() method. And I really don't understand the override keyword.

2 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Hariidaran,

Amit is defining a different implementation for the method discountedPrice() for the Clothing subclass. Since the method exists in the parent class (Product), he must use the keyword override to tell Swift, "hey, I know this method already exists since I subclassed Product, but I want to make it do something different for Clothing; I want to override the existing method definition."

There's a problem, though - the entire implementation of this method is now coded twice (all he's changed is the parameters). With a very simple method like this (one return line that's just basic math that won't change), this isn't really a big deal. You can imagine, though, a much more complex method that does many more calculations and maybe displays a message, etc. It would be a terrible idea to write the code for this in two places (Product's method definition and Clothing's method definition). If you ever wanted to change something in the Product method (say a typo in one of the messages you were displaying), you would have to be sure to change it in the Clothing method too. If, instead, you simply call super.discountedPrice() in Clothing, then any changes you make to the Product method will automatically translate to the Clothing method. That is the key advantage of using DRY principles.

Let me know if that makes sense.

Cheers,

Greg