What is the difference between class and instance methods?
Asked Answered
N

18

464

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 everything else?

Nice answered 27/6, 2009 at 20:48 Comment(0)
C
683

Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

They could then be used like so:

[MyClass aClassMethod];

MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];

Some real world examples of class methods are the convenience methods on many Foundation classes like NSString's +stringWithFormat: or NSArray's +arrayWithArray:. An instance method would be NSArray's -count method.

Coarse answered 27/6, 2009 at 21:19 Comment(5)
Good answer. It's also worth noting that you'll see a particular shorthand notation for describing methods. For example, +[NSString stringWithFormat:] is the class method +stringWithFormat: on NSString; -[NSArray objectAtIndex:] is an instance method. Methods with multiple selector parts are written like -[NSMutableDictionary setObject:forKey:] etc. You'll often see this notation in Cocoa responses, documentation, and in Xcode.Stella
I would add that a class method is called a "static" method in many other languages. And to answer the original question, accessors are instance methods because they are setting and getting the state of a specific instance. In the above example, NSArray count returns the number of objects in a specific instance.Griff
"whereas a class method can be used with just the class name." or the class objectSanbo
Sorry for my excitement... but i just learnt the difference, and its potential. class methods rock and so do singleton classes! ufff I've fallen in love! <3Mohair
@BrianPan static and class methods are not the same. They are similar but the reason they are named differently is that they work differently. For example, static methods cannot be overriden.Elizbeth
H
196

All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:

enter image description here

A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.

enter image description here

An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.

Huskamp answered 8/5, 2013 at 8:1 Comment(4)
@JohannesFahrenkrug Nicely explained the concept for class and object here .Isn't the actual question is for difference between class method and an instance method ;Ewens
@Aiden Thank you. Yes, you are right, the question was actually about instance methods vs class methods. However, the OP's question showed that the concept of class vs instance was not really clear to him. Once that concept is clear, the other parts fall into place.Huskamp
Perfect explanation of Class vs Instance of a class. Classes are a strange concept to newbies and this explains it in its most fundamental way.Hieroglyphic
@JohannesFahrenkrug really a good explanation, which made me to think how boths r diff and when to use bothAllan
P
105

Like the other answers have said, instance methods operate on an object and has access to its instance variables, while a class method operates on a class as a whole and has no access to a particular instance's variables (unless you pass the instance in as a parameter).

A good example of an class method is a counter-type method, which returns the total number of instances of a class. Class methods start with a +, while instance ones start with an -. For example:

static int numberOfPeople = 0;

@interface MNPerson : NSObject {
     int age;  //instance variable
}

+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
@end

@implementation MNPerson
- (id)init{
    if (self = [super init]){
          numberOfPeople++;
          age = 0;
    }    
    return self;
}

+ (int)population{ 
     return numberOfPeople;
}

- (int)age{
     return age;
}

@end

main.m:

MNPerson *micmoo = [[MNPerson alloc] init];
MNPerson *jon = [[MNPerson alloc] init];
NSLog(@"Age: %d",[micmoo age]);
NSLog(@"%Number Of people: %d",[MNPerson population]);

Output: Age: 0 Number Of people: 2

Another example is if you have a method that you want the user to be able to call, sometimes its good to make that a class method. For example, if you have a class called MathFunctions, you can do this:

+ (int)square:(int)num{ 
      return num * num;
}

So then the user would call:

[MathFunctions square:34];

without ever having to instantiate the class!

You can also use class functions for returning autoreleased objects, like NSArray's

+ (NSArray *)arrayWithObject:(id)object

That takes an object, puts it in an array, and returns an autoreleased version of the array that doesn't have to be memory managed, great for temperorary arrays and what not.

I hope you now understand when and/or why you should use class methods!!

Paternoster answered 27/6, 2009 at 21:57 Comment(3)
micmoo, might I suggest you put the "static int numberOfPeople = 0;" in code formatted text? I was confused until I noticed it above the sample code. Other than that, a really concise answer.Overhasty
Pardon my newbie confusion, but why do you need both instance variable "age" and instance method "age"? Won't getter and setter for instance variable "age" be created with @synthetize?Alum
@Alum "age" would have to be defined as a property in order to use synthetize.Judiciary
R
38

An instance method applies to an instance of the class (i.e. an object) whereas a class method applies to the class itself.

In C# a class method is marked static. Methods and properties not marked static are instance methods.

class Foo {
  public static void ClassMethod() { ... }
  public void InstanceMethod() { ... }
}
Roselinerosella answered 27/6, 2009 at 20:51 Comment(2)
Argh - sorry, I just noticed this was an Obj-C question. Hopefully my answer still applies but please vote down or vote to delete.Roselinerosella
No harm done. The first part of your answer is correct as a general OOP principle, and it definitely applies to Objective-C. You can add "objective-c" to your list of tags to ignore if you don't want to see such questions, although any participation is certainly welcome. :-)Stella
E
16

The answer to your question is not specific to objective-c, however in different languages, Class methods may be called static methods.

The difference between class methods and instance methods are

Class methods

  • Operate on Class variables (they can not access instance variables)
  • Do not require an object to be instantiated to be applied
  • Sometimes can be a code smell (some people who are new to OOP use as a crutch to do Structured Programming in an OO enviroment)

Instance methods

  • Operate on instances variables and class variables
  • Must have an instanciated object to operate on
Erdah answered 27/6, 2009 at 20:57 Comment(1)
Instance methods can operate on class variables?Handout
A
16

I think the best way to understand this is to look at alloc and init. It was this explanation that allowed me to understand the differences.

Class Method

A class method is applied to the class as a whole. If you check the alloc method, that's a class method denoted by the + before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.

Instance Method

You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init for example (denoted with a - before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.

Example

NSString *myString = [NSString alloc];

You are calling the class method alloc in order to generate an instance of that class. Notice how the receiver of the message is a class.

[myString initWithFormat:@"Hope this answer helps someone"];

You are modifying the instance of NSString called myString by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).

Accusatorial answered 7/11, 2012 at 9:50 Comment(2)
What do you mean by check the "alloc" method? Can you point me to a specific place in documentation? (edit) --> ahh nevermind, yeah in the NSObject docs it says that under "Tasks" - developer.apple.com/library/ios/documentation/cocoa/reference/…Toddle
You don't really need to understand what it does really to grasp this, just that it is applied to the class. Put simply: alloc allocates enough memory for the object, init will modify what's in those memory addresses to define the state of the object. We can't modify an object unless there's a space to modify it in, so we use alloc on the class which will decide give us that space.Accusatorial
T
6

Class methods are usually used to create instances of that class

For example, [NSString stringWithFormat:@"SomeParameter"]; returns an NSString instance with the parameter that is sent to it. Hence, because it is a Class method that returns an object of its type, it is also called a convenience method.

Tahoe answered 9/11, 2010 at 6:16 Comment(0)
C
6

So if I understand it correctly.

A class method does not need you to allocate instance of that object to use / process it. A class method is self contained and can operate without any dependence of the state of any object of that class. A class method is expected to allocate memory for all its own work and deallocate when done, since no instance of that class will be able to free any memory allocated in previous calls to the class method.

A instance method is just the opposite. You cannot call it unless you allocate a instance of that class. Its like a normal class that has a constructor and can have a destructor (that cleans up all the allocated memory).

In most probability (unless you are writing a reusable library, you should not need a class variable.

Cichlid answered 24/5, 2013 at 1:35 Comment(1)
An obvious case where you need class methods is the creation of instances. You must be able to create instances without having any instances yet, otherwise the first instance could never be created. That's why +alloc is and must be a class method.Gerrygerrymander
E
4

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

Echt answered 27/6, 2009 at 20:51 Comment(0)
A
3

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.

Aerometry answered 16/11, 2011 at 10:17 Comment(0)
S
3

class methods

are methods which are declared as static. The method can be called without creating an instance of the class. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.

Instance methods

on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. Instance methods are not declared as static.

Spectral answered 7/11, 2012 at 9:34 Comment(1)
It can also be created with "alloc" keyword not only the "new". Also, Objective-C does not demand an instance to exist to call an instance method, you can send messages to a null pointer.Chrysa
B
3

In Objective-C all methods start with either a "-" or "+" character. Example:

@interface MyClass : NSObject
// instance method
- (void) instanceMethod;

+ (void) classMethod;
@end

The "+" and "-" characters specify whether a method is a class method or an instance method respectively.

The difference would be clear if we call these methods. Here the methods are declared in MyClass.

instance method require an instance of the class:

MyClass* myClass = [[MyClass alloc] init];
[myClass instanceMethod];

Inside MyClass other methods can call instance methods of MyClass using self:

-(void) someMethod
{
    [self instanceMethod];
}

But, class methods must be called on the class itself:

[MyClass classMethod];

Or:

MyClass* myClass = [[MyClass alloc] init];
[myClass class] classMethod];

This won't work:

// Error
[myClass classMethod];
// Error
[self classMethod];
Backfire answered 4/2, 2015 at 9:41 Comment(0)
T
3

CLASS METHODS


A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.


INSTANCE METHODS


An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.


INVOKE


To invoke an instance method, you send the message to an instance of the class.

To invoke a class method, you send the message to the class directly.


Source: IOS - Objective-C - Class Methods And Instance Methods

Takakotakakura answered 23/1, 2016 at 18:10 Comment(0)
P
2

Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.

Pokpoke answered 17/3, 2011 at 15:55 Comment(1)
-1 from me, because you can pass instance to the class method and it will be able to change and know it's variables' values.Chrysa
H
1

Also remember, the same idea applies to variables. You will come across terms like static, member, instance, class and so on when talking about variables the same as you would for methods/functions.

It seems the common term in the Obj-C community is ivar for instance variable, but I am not an Obj-C guy, yet.

Hereunder answered 18/1, 2012 at 14:12 Comment(0)
W
1

An update to the above answers, I agree instance methods use an instance of a class, whereas a class method can be used with just the class name.

There is NO more any difference between instance method & class method after automatic reference counting came to existence in Objective-C.

For Example[NS StringWithformat:..] a class method & [[NSString alloc] initwihtformat:..] an instance method, both are same after ARC

Wesla answered 25/2, 2013 at 7:2 Comment(0)
F
1

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.

Ferromagnesian answered 12/6, 2016 at 19:18 Comment(0)
D
0

Adding to above answers

Class method will work on class, we will use this for general purpose where like +stringWithFormat, size of class and most importantly for init etc

NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat]; 

Instance Method will work on an instance of a class not on a class like we are having two persons and we want to get know the balance of each separately here we need to use instance method. Because it won't return general response. e.g. like determine the count of NSSArray etc.

[johnson getAccountBalance];
[ankit getAccountBalance];
Discourse answered 8/2, 2017 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.