Monday, December 19, 2011

Objective C from a Java Developer perspective Part I

We are witness how mobile development is spread across the IT industry with rising of Apple’s iPhone and Google’s Android. There are many other mobile platforms like J2ME, BlackBerry, Symbian, Windows Mobile 7 that are trying to take a pace from the mobile cake but as we see currently Android and iOS are leading mobile platforms.

In this document I’ll try to make comparison between Java and Objective C as main languages for developing on those mobile platforms.

Objective C is main programming language for developing on Mac OSx. Its developed as C/C++ alternative based on SmallTalk which covers whole OOP paradigm. As language, is a little bit different than any other C like language but compared for example with Java is much more simpler. In the following text I’ll try to make simple comparison between Java and Objective C and to explain the differences.

Variables and Methods

In the table below Objective C variable primitive types and class types are displayed with same Java alternative.

Objective C
Java
id
NSObject
NSInteger
NSString
BOOL
NSFloat
NSNumber
NSData/NSMutableData
NSArray
NSMutableArray
NSMutableDictionary
NSSet
NSDate
NSCalendar
Int
long
long long
bool
float
double
char
-
short
Class
Object
Integer
String
Boolean
Float
-
Byte
[]
List
Map
Set
Date
Calendar
Int
long
-
boolean
float
double
char
byte
short

As we can see, primitive types, class types and collections are very similar in both languages.For every type in Objective C we have almost the same type in Java.

Initialization on primitive types is same in both languages but on class types and on collections is a little bit different. In the next table we can see those differences.

Objective C
Java
int test = 0;
char name = ‘John Doe’;
NSInteger *number = [[NSInteger alloc] init];
NSString *stringType = [[NSString alloc] init];
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSNumber *genericNumber = [[NSNumber alloc] numberWithInt:1];
int test = 0;
char name = ‘j’;
Integer number = new Integer();
String stringType = new String();
List dataList = new LinkedList();
-

Testing for the class type is made like this:
isKindOfClass
instanceof

Setting/Getting the object from the Collections

Objective C
Java
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:@”Test”];
[arr addObject:@”Test 2”];
NSString *testObj = [arr objectAtIndex:0];
id *testObj = (NSString *)[arr objectAtIndex:0];
1. List objList = new LinkedList();
2. ListobjList = new LinkedList();
objList.add(new String(“Test”));
objList.add(new String(“Test 2”));
1. String testObj = (String)objList.get(0);
2. String testObj = objList.get(0);

In Objective C collections can keep mixed type of objects, same in Java except that in Java we can use generics to set which type of objects we’ll keep in our list. Casting work same in both languages.

Static constants in Objective C are declared as #define macro directive, same for int and char where in Java with using special keywords static and final, for example:

Objective C
Java
#define NUMBER_OF_MONTHS 12
#define YEAR _ATTRIBUTE @”year”
public static final int NUMBER_OF_MONTHS = 12;
public static final String YEAR _ATTRIBUTE = “year”;

We can set static keyword to the property in Objective C but that not mean that work same as in Java, static keyword mean that the property is visible inside that class but if we want that property to be visible outside that class we should implement static accessors methods for each static property. In the table we’ll see also method definition in both languages and returning type.

Objective C
Java
@interface MyClass
{
NSString myVar;
}
+ (NSString *)myVar;
+ (void)setMyVar:(NSString *)newVa;
@end
@implementation MyClass
static NSString *myVar;
+ (NSString *)myVar { return myVar; }
+ (void)setMyVar:(NSString *)newVar { myVar = newVar; }
@end
[MyClass setMyVar:@”Test Value”];
NSLog(@”%@”,[MyClass myVar]);
public class MyClass {
public static String myVar;
public static String getMyVar(){ return this.myVar;}
public static void setMyVar(String myVar) {
this.myVar = myVar;
}
}
MyClass.myVar = “Test Var”;
System.out.println(MyClass.getMyVar());

Sign plus (“ + “) is used for making the method static instead of using sign minus (“ – “) for not static methods.

Methods work same in both languages, the difference is only in declaration of returning type and in passing arguments.

Objective C
Java
-(void)executeWithoutResult { }
-(void)executeByName: ( NSString *)name { }
-(void)executeByNameAndAge: (NSString *)name age: (int)age { }
-(NSString *)findUserById: (int)userId { }
+(int)findUserAges: (int)userId { }
public void executeWithoutResult() { }
public void executeByName(String name) { }
public void executeByNameAnd Age(String name, int age) { }
public String findUserById(int userId) { }
public int findUserAges (int userId) { }
Depending on sign plus (“ + “ ) or minus (“ – “ ) method will be static or not. After the sign we put the returning type in small brackets. Depending on returning type we can return primitive type, or Class type pointer. After the brackets method name is defined. After the method name we put colon for method parameters declaration. Before every parameter we put the parameter type. Parameters are separated with space. Parameters are declared as, parameter name colon parameter type in brackets and after that again parameter name. After last parameter we open curly bracket for methods body.
Calling the methods is also different in both languages. Objective C use message passing system for executing instance methods where in Java methods are called with dot between the object and method we want to call.
Classes and objects
Class implementation is different in both languages. In Objective C custom class must inherit from NSObject, where in Java everything inherits from Object. In Java simple classes are known as POJO or Plain Old Java Object. These classes may encapsulate properties with different data types also they may or may not contain methods used for getting and setting the properties. In the table below we can see implementation in both languages.
Objective C
Java
CustomObject.h
@interface CustomObject:NSObject{
@public
NSString *stringValue_;
@private
NSInteger *integerValue_;
}
@property(nonatomic, assign) NSString *stringValue;
@property(nonatomic, assign) NSInteger *integerValue;
@end
CustomObject.m
#import “CustomObject.h”
@implementation CustomObject
@synthesize stringValue = stringValue_;
@synthesize integerValue = integerValue_;
-(id)init{
self = [super init];
if(self){
//call init methods
}
return self;
}
-(void)dealloc{
stringValue = nil;
[integerValue release];
[super dealloc];
}
@end
CustomObject.java
public class CustomObject{
public String stringValue;
private Integer integerValue;
public CustomObject(String stringValue, Integer integerValue){
this.stringValue = stringValue;
this.integerValue = integerValue;
}
public String getStringValue(){
return this.stringValue;
}
public void setStringValue(String stringValue){
this.stringValue = stringValue;
}
public Integer getIntegerValue(Integer integerValue){
return this.integerValue;
}
public void setIntegerValue(){
this.integerValue = integerValue;
}
}

Initialization and setting/getting the values from the properties

CustomObject *obj = [[CustomObject alloc] init];
obj.stringValue = @”Test Value”;
[obj setStringValue:@”Test Value”];
NSLog(“%@”, obj.stringValue);
NSLog(“%@”, [obj getStringValue]);
[obj release];
CustomObject obj = new CustomObject();
obj.stringValue = “Test Value”;
obj.setStringValue(“Test Value”);
System.out.println(obj.stringValue);
System.out.println(obj.getStringValue());

As we see in the table implementation on classes in Objective C is a little bit bigger then in Java when we have small number of properties, but in case when we have bigger number of properties if we use getters/setters in Java, the code will be much more bigger then in Objective C. Why?

In Objective C classes are implemented in two different files, one for interface and the other one for implementation, in special cases for private access to some properties, beside the required interface, we can implement interface also at the beginning of the file where we our class is implemented. We can set access type to the properties by setting @public, @private, @protected above the block of properties where in Java special access keywords are put at the beginning of the each property definition. For restricting access to the methods, in Java we set one of three access keywords before the method declaration where in Objective C that is done with duplicate interface definition at the beginning of the class implementation and with private implementations:

@interface MyClass(Private){
-(void)someMethod;
}
@end
@implementation MyClass
-(void)someOtherMethod {}
@end
@implementation MyClass (Private)
-(void)someMethod {}
@end
public interface IMyClass{
private void someMethod();
}
public MyClass implements IMyClass{
private void someMethod() {}
}
Where in Java we can use interface or just put set the method as private. Classes in Objective C are always pubic where in Java we can also set access rights to the class or interface which will restrict access the that class or interface. Special keyword @synthesize will automatically create getters/setters for our properties, that’s not mean that we can’t implement getters/setters by our self, but this keyword is mostly used. In Java we can implement interface in separate file and then our class will implement that interface, we can implement the interface at the beginning of the file where our class is implemented ( but this is bad practice ), and also we can implement the class without using the interface as we saw in the example. In every class implementation in Objective C there are also two methods that should be implemented, init and dealloc. Init method is same as constructor in Java, but if we not implement this method, the init method will be called from the super class that we extends, same for dealloc. We can have many different init methods same as constructors and each of them can be used in different situations, but only one dealloc method in the class must be implemented. Dealloc method Is used for deallocating reserved memory for instance and class variables, local variables are deallocated at the end of each method.
Protocols and delegates

In the next part i'll make brief comparison between Objective C protocols and delegates and Java alternatives.