Objective C's SmallTalk message passing syntax can seem a little alien to Java developers who are used to C-style syntax languages (C, Java, PHP etc.)
This little crib sheet will show how the major features will translate.
Objective C interfaces are more like C header files than Java interfaces since they also define class members (variables) rather than just the method interface to an object.
Let's start with a simple class to represent a FlashCard (a simple card with a colour and a name). There is a two-parameter constructor and a parameterless interface method defined "display" which simply logs the name variable to the standard out.
Here is the Java interface and class
IFlashCard.java
package com.chrisnewland.flashcard;
public interface IFlashCard
{
public void display();
}
public interface IFlashCard
{
public void display();
}
FlashCard.java
package com.chrisnewland.flashcard;
import java.awt.Color;
public class FlashCard implements IFlashCard
{
private Color colour;
private String name;
public FlashCard(Color colour, String name)
{
this.colour = colour;
this.name = name;
}
@Override
public void display()
{
System.out.println("Name: " + name);
}
}
import java.awt.Color;
public class FlashCard implements IFlashCard
{
private Color colour;
private String name;
public FlashCard(Color colour, String name)
{
this.colour = colour;
this.name = name;
}
@Override
public void display()
{
System.out.println("Name: " + name);
}
}
And here is the Objective-C
FlashCard.h
#import <Foundation/Foundation.h>
@interface FlashCard : NSObject {
@private
NSString* name;
UIColor* color;
}
@property(readonly) NSString* name;
@property(readonly) UIColor* color;
-(id)initWithName:(NSString*)theName andColor:(UIColor*)theColor;
-(void)display;
@end
@interface FlashCard : NSObject {
@private
NSString* name;
UIColor* color;
}
@property(readonly) NSString* name;
@property(readonly) UIColor* color;
-(id)initWithName:(NSString*)theName andColor:(UIColor*)theColor;
-(void)display;
@end
FlashCard.m
#import "FlashCard.h"
@implementation FlashCard
@synthesize name, color;
-(id) initWithName:(NSString *)theName andColor:(UIColor *)theColor
{
if (self = [super init])
{
name = theName;
color = theColor;
}
return self;
}
-(void)display {
NSLog(@"Name: %@", name);
}
@end
@implementation FlashCard
@synthesize name, color;
-(id) initWithName:(NSString *)theName andColor:(UIColor *)theColor
{
if (self = [super init])
{
name = theName;
color = theColor;
}
return self;
}
-(void)display {
NSLog(@"Name: %@", name);
}
@end