What is the difference between class and instance methods?

后端 未结 18 2211
说谎
说谎 2020-11-21 11:55

What\'s the difference between a class method and an instance method?

Are instance methods the accessors (getters and setters) while class methods are pretty much ev

18条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 12:46

    Take for example a game where lots of cars are spawned.. each belongs to the class CCar. When a car is instantiated, it makes a call to

    [CCar registerCar:self]
    

    So the CCar class, can make a list of every CCar instantiated. Let's say the user finishes a level, and wants to remove all cars... you could either: 1- Go through a list of every CCar you created manually, and do whicheverCar.remove(); or 2- Add a removeAllCars method to CCar, which will do that for you when you call [CCar removeAllCars]. I.e. allCars[n].remove();

    Or for example, you allow the user to specify a default font size for the whole app, which is loaded and saved at startup. Without the class method, you might have to do something like

    fontSize = thisMenu.getParent().fontHandler.getDefaultFontSize();
    

    With the class method, you could get away with [FontHandler getDefaultFontSize].

    As for your removeVowels function, you'll find that languages like C# actually have both with certain methods such as toLower or toUpper.

    e.g. myString.removeVowels() and String.removeVowels(myString) (in ObjC that would be [String removeVowels:myString]).

    In this case the instance likely calls the class method, so both are available. i.e.

    public function toLower():String{
      return String.toLower();
    }
    
    public static function toLower( String inString):String{
     //do stuff to string..
     return newString;
    }
    

    basically, myString.toLower() calls [String toLower:ownValue]

    There's no definitive answer, but if you feel like shoving a class method in would improve your code, give it a shot, and bear in mind that a class method will only let you use other class methods/variables.

提交回复
热议问题