Home Iphone Objectivec Objective C Constructors
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Objective C Constructors

Advertisement
Objective-C enables user to define constructor with the help of self and super keywords.

Objective C Constructors

     

Objective-C enables user to define constructor with the help of self and super keywords. Like java Objective-C has parent class and programmer can access its constructor by statement [super init], this statement returns a instance of parent class which we assign to the 'self' keyword, actually 'self' plays same role as this keyword in C++ and Java. The default constructor is -(id) init statement if(self) is used to check the condition self != nil to confirm that parent class returned a new object successfully.

Example:

MyClass.h
#import<Foundation/NSObject.h>
@interface MyClass:NSObject{
int a;
int b;
}
// declare constructor
-(MyClass*) set:(int) a andb:(int) b;
-(void) sum;
@end

MyClass.m

#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
// define constructor
-(MyClass*) set:(int) x andb:(int) y {
  self = [super init];
  if(self) {
    a=x;
    b=y;
    return self;
}
}
-(void) sum {
printf("Sum is : %d",a+b);
}
@end

MyClassMain.m

#import<stdio.h>
#import"MyClass.m"
int main(){

// use constructor
MyClass *class = [[MyClass alloc] set : 10 andb : 12];
[class sum];
[class release];
return ;
}

Output:

Sum is : 22

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 24, 2009

Ask Questions?    Discuss: Objective C Constructors   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Ryan
December 29, 2011
Wrong code

-(MyClass*) set:(int) x andb:(int) y { self = [super init]; if(self) { a=x; b=y; return self; } -(MyClass*) set:(int) a andb:(int) b; Do not match. The method argument should be -(MyClass*) set:(int) x andb: (int) y;
Anirban Roy
July 13, 2012
Objective C

Hi Team, I am very new in this technology .I want to learn the technology properly .Please help me sending anything that relates TO ANY VALID BASIC Objective C . Thanks & Regards, Anirban Roy
DMCA.com