What is the difference between class and instance methods?

后端 未结 18 2512
说谎
说谎 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:55

    Note: This is only in pseudo code format

    Class method

    Almost does all it needs to do is during compile time. It doesn't need any user input, nor the computation of it is based on an instance. Everything about it is based on the class/blueprint——which is unique ie you don't have multiple blueprints for one class. Can you have different variations during compile time? No, therefore the class is unique and so no matter how many times you call a class method the pointer pointing to it would be the same.

    PlanetOfLiving: return @"Earth" // No matter how many times you run this method...nothing changes.
    

    Instance Method

    On the contrary instance method happens during runtime, since it is only then that you have created an instance of something which could vary upon every instantiation.

    initWithName: @"John" lastName: @"Doe"Age:12 @"cool"
    initWithName: @"Donald" lastName: @"Drumpf"Age:5 attitude:@"He started"
    initWithName: @"President" lastName: @"Obama"Age:54 attitude: @"Awesome"
    //As you can see the value can change for each instance.
    

    If you are coming from other languages Static methods are same as class methods.
    If you are coming from Swift, type methods are same as class methods.

提交回复
热议问题