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 trialDatabase Admin
iOS Development Techdegree Student 201 PointsWhy don't we just use Static Functions
I am aware what static function in a class can do but I am curious why we don't declare a function inside a class as static so that we don't need to create a instance of that class.
For example in ItunesAPIClient class, we are just using functions of that class and not monitoring the state and properties of that class. Why don't we just declare the functions as static and use as ItunesAPIClient.download() instead of creating a instance then calling the instance function.
1 Answer
JS Goupil
11,309 PointsHey! So there's a key reason why we don't do that. There's a great advantage to object oriented programming, and creating instances is a key part. For example, you are making a game with different kinds of monsters. So you define a class called Monster which stores different attributes such as its health and damage. Those would be something like doubles. Now that you have a class called Monster to model your monster, you can create more than one monster. Again, try to think of the Monster class as a model or a blueprint, for all the monsters you want to create. You can now have monster1, monster2, monster3, etc.
Each monster has its own health and damage ability. Now say monster1 loses health. Now you want your Monsters to be able to self heal. You would write a function in the monster class to do that. However, you wouldn't want static, you want it to be able to heal ITSELF and ITS OWN health. Remember that although monster1 and monster2 are both instances of the Monster class, they don't share the same health and damage properties. And its the same thing with the function, you want each monster to own its own healing ability to heal itself. If you declared it as static, it wouldn't make use of a function on an instance that doesn't exist right?