Sunday, October 3, 2010

Java Vs Objective C: Object Method Invocation to Object Messaging

I recently started looking into iphone and ios app development. The primary language for ios based applications is Objective C, which is an object oriented C like language. Coming from Java background there are certain aspects and concepts in the Objective C language, which are different for a Java programmer.

So here I am starting a series of blog posts, to give an overview of Objective C language and contrast it with Java programming language.

In this blog, I want to compare Java object method invocation to Objective C object messaging. They are pretty much doing the same thing.

In Java you define a class and methods which can be invoked on the object of this class. For example let say you have a class called Window and it has a method called getBounds which returns Rectangle bounds of the Window. It can looks something like this:
public class Window {
private Rectangle myBounds;

Rectangle getBounds() {
return this.myBounds;
}

}

And this is how you invoke a method on an object:
Window window = new Window();
Rectangle rect = window.getBounds();

In Objective C you will define a class by first defining an interface in the header file. Here in Window interface we have defined a method called bounds:
@interface Window : NSObject {
CGRect *rect;
}
- (CGRect*) bounds;

and then in class file you define the implementation:
@implementation Window
- (CGRect*) bounds {
return rect;    
}

@end

Objective C messaging:
In objective C to call a method of an object you do it by messaging an object.A message is the method signature, along with the parameter information the method needs.Messages are enclosed by brackets ([ and ]). Inside the brackets, the object receiving the message is on the left side and the message (along with any parameters required by the message) is on the right.

For example to invoke bounds method on an instance of Window object you use messaging like shown below:
//create an instance of Window by messaging alloc on Window class. alloc is like static
//method on Window class
Window *window = [Window alloc];
//now call bounds on window
CGRect *rect = [window bounds];


This shows how messaging works in Objective C. In future blogs we will look at other features of Objective C language.

Promote your blog

No comments:

Post a Comment