SlideShare una empresa de Scribd logo
1 de 39
More on class, Interitance, Polymorphism 
Chhorn Chhaly 
Leang Bunrong 
Cheng Udam 
Kan Vichhai 
Srou Chanthorn 
Em Vy 
Seth Sambo 
Chea Socheat
Content 
• Interface and Implement file 
• Multiple Arguments to Method, Local Variable, Static Variable 
• Self Keyword and Return Object 
• Inheritance 
• Overriding Method 
• Abstract Class 
• Polymorphism 
• Dynamic Typing and Dynamic Binding 
• Exception
Interface and Implementation files(class) 
 Objective-C separated two files to manage declaration area and definition area. 
1. Interface file has extension .h (header file).it is used to declare fields,properties,methods. 
2. Implementation file has extension .m (execute file). It is used to implement method 
bodies. 
 In objective – C to create class we need two files .h and .m so interface file plus 
implementation file 
equal to create class in objective – C.
Interface and Implementation files (cont.) 
 Interface files (.h) 
All fields must declare in “{ fileds }”. “{ }” is 
omitted when no field declaration. Methods and 
properties are declare outside of “{ }”. 
 Notice: In Objective – C we can declare fields in interface file but it recommend that should 
not declare here because data encapsulation. You should declare in implementation file.
Interface and Implementation files (cont.) 
 Interface files (.h) example:
Interface and Implementation files (cont.) 
 Implementation file(.m) 
Fields should declare here for data encapsulation.
Interface and Implementation files (cont.) 
 Implementation file(.m) example:
Synthesized Accessor Method 
 synthesized: 
Synthesized keyword is used to create getter and setter method in objective – C (version older 
than 2.0 and version 2.0).but nowadays we don’t need to use it because Xcode tool add more 
features that it generate setter and getter method automatically for our projects. 
 Syntax: 
@synthesize propertyname; 
Or @synthesize propertyname=_propertyname; 
 Sometime, we declared properties without fields instance of class so synthesize keyword 
also generate instance fields of class that begin with symbol “_”.
Synthesized Accessor Method 
 Synthesized keyword example: 
 Both files( .m and .h) we didn’t declare field. so synthesize keyword will generate field( 
instance variable of class) for samename property that field beging with symbol “_” 
 ( _samename).
Accessing Property 
 Access through normal messaging syntax: 
[ object setProperty:NewValue] 
[object property]
Accessing Property 
 Access via dot syntax(Objective – C version 2.0): 
Object.property; 
Object.property=NewValue;
Multiple Arguments to methods 
• In Java: 
void functionX(int x, int y, int z){ 
//statement 
} 
Object.functionX(x, y, z); //Calling function 
• In Objective-c: 
-(void) functionX:(int)x withY:(int)y, withZ:(int)z; 
[Object functionX:x withY:y withZ:z];
Method without argument name 
• When creating the name for a method, the argument names are actually optional. For example, 
you can declare a method like this: 
-(int) set: (int) n: (int) d; 
• Note that, unlike in previous examples, no name is given for the second argument to the method 
here. This method is named set:: , and the two colons mean the method takes two arguments, 
even though they’re not all named. 
• To invoke the set:: method, you use the colons as argument delimiters, as shown here: 
[aFraction set:1 :3]; 
• It’s not good programming style to omit argument names when writing new methods because 
• it makes the program harder to follow and makes the purpose of the method’s actual parameters 
less intuitive.
Local Variable 
• Local variable refers to variables located inside a block of code, a method or a function 
Example: 
- (void) fishing{ 
Int fish = 0; 
Int banana = 8; 
While(fish < 0){ 
banana = banana+1; 
} 
- } 
Local variables that are basic C data types have no default initial 
value, so you must set them to some value before using them. 
Local object variables in Objective-c are initialized to nil by default.
Method Arguments 
• The names you use to refer to a method’s arguments are also local variables. Suppose 
you had a method called calculate: , defined as follows: 
-(void) calculate: (double) x { 
x *= 2; 
//another statement 
}
The Static keyword 
• You can have a local variable retain its value through multiple invocations of a method 
by placing the keyword static in front of the variable’s declaration. 
Example: 
static int hitCount = 0; 
• Unlike other local variables, which are basic data types, a static variable does have an 
initial value of 0 , so the initialization shown previously is redundant. Furthermore, they 
are initialized only once when program execution begins and retain their values through 
successive method calls.
Self keyword 
• Is a special variable in objective-c, inside instance method this variable refer to the 
receiver (instance) of the Message that invoke the method, while a class self indicate 
which class is calling. 
@import “A.h” 
@implementation A 
-(void)print:(NSString *)message{ 
NSLog(@”%@”,message) 
} 
-(void) saySomething{ 
[self print : @”Hello World”]; 
}@end 
Note : we can called instance method from self 
variable. because self variable is refer to the instance 
of the current class. 
In this example we call instance method print from 
self key-word inside the method saySomething() 
It is possible for use self instead of create the new 
instance method of the current class.
Returning object 
• Class is also data type. Data type use precede of identifier to refer what kind of type that 
identifier can be accept. Data type can also use for method to refer what kind of data 
that method will return. 
-(Fraction *) add:(Fraction *)f; Note : 
Add:method will return a Fraction object 
and that it will take one as it argument as 
well. This method will return Fraction object 
value to the sender of the message with 
the return statement.
Inheritance 
• What is inheritance? 
 Inheritance is a technique that a new class is derived or inherited from an existence class. 
• What is subclasses, based classes? 
 We can call subclasses as derived classes, child classes – the class that inherit from the based class. 
 We can call based classes as parent classes, superclass – the class that was inherited by 
subclasses. 
• Why inheritance? 
 Inheritance provides us many advantages such as: 
o Reusability – no need to write code again and again. 
o Expendability – extends more methods the superclass. 
o Overriding – we can also override the superclass methods if it doesn’t match with our problem.
Inheritance 
• In Objective-C, it is allow only single inheritance not multi inheritance. 
• Subclasses can only take non-private properties and methods only. 
• In Objective-C, every classes must inherit from the root class. NSObject is the root class 
in Objective-C. 
• What is root class? 
 Root class is a class that doesn’t have parent at the top of it. Example: NSObject.
Inheritance 
• Here is example of what our inheritance look like: 
#import <Foundation/Foundation.h> 
//SuperClass declaration and definition 
@interface SuperClass: NSObject{ 
int x; 
} 
-(void) initX; 
@end 
@implementation SuperClass 
-(void) initVar{ 
x=100; 
} 
@end 
@ 
In java: 
public class SuperClass extends NSObject{ 
public int x; 
public void initX(){ 
x=100; 
} 
}
Inheritance 
• @interface SuperClass: NSObject 
1 2 3 4 
o 1: @inhterface – it is similar to the class keyword in java. 
o 2: SuperClass – our class name. 
o 3: “:” – extends 
o 4: NSObject – SuperClass
Inheritance 
• Now, let create another class and extend from our SuperClass class. And we also want 
to add some more method for that class. 
#import<Foundation/Foundation.h> 
@interface SubClass: SuperClass 
-(void) printVar; 
@end 
@implementation SubClass 
-(void) printVar{ 
NSLog(@”The value of x is: %i”,x); 
} 
@end 
#import “SubClass.h” 
int main (int argc, char *argv[]){ 
@autoreleasepool{ 
SubClass *sub=[[SubClass init] 
alloc]; 
[sub initVar]; 
[sub printVar]; 
} 
return 0; 
}
Inheritance 
• After seeing some examples above, we can say that: 
 NSObject has SuperClass as its subclass and SuperClass also has SubClass as its subclass. 
 Or we can say that, SubClass has SuperClass as its superclass and SuperClass has 
NSObject as its superclass. 
NSObject 
SuperClass 
SubClass 
subclass 
superclass 
subclass superclass
Inheritance 
• The @class Directive: 
 This will tell compiler that you will use that class in our code. 
 It will not import the header file and therefore will compile a little faster. 
• What is the differences between @class and #import? 
 @class – it will tell our compiler that we will use one class. But we cannot use methods or 
properties from that class. Because we not include the whole “.h” header file. 
 #import - it will actually import the header file during compilation and is needed when we 
want to use the members of that class. That is how the compiler knows what properties, 
methods, etc can be used safely.
Overriding Methods 
• Overriding is the action of replacing a method from a superclass with a more specific 
version of itself. 
• Overriding methods is the primary way by which you can customize the behavior of the 
classes participating in a hierarchy. 
• It’s like Java, the overriding method has the same name, number and type of 
parameters, and return type as the method it overrides.
Overriding Methods(Cont.) 
Example : We have two classes, Person and Student 
• Person Class 
@interface Person : NSObject{ 
int age; 
} 
-(void)initAge:(int)a; 
@end 
---------------------------- 
@implementation Person 
-(void)initAge:(int)a 
{ 
age = a; 
} 
@end 
• Student Class 
@interface Student : Person 
//Overriding Method 
-(void)initAge:(int)a; 
-(void)displayAge; 
@end 
--------------------------- 
@implementation Student 
-(void)initAge:(int)a{ 
age=a; 
} 
-(void)displayAge{ 
NSLog(@"Your age is %i",age); 
} 
@end 
• Main 
Student * stu =[Student new]; 
[stu initAge:20]; 
[stu displayAge];
Abstract Class 
• In general, abstract class is the class, which typically incomplete by itself and cannot be 
instantiated, but contains useful code that reduce the implementation of its subclasses. 
• As we know in Java we mark abstract class by the abstract keyword and all its subclass 
must have implement all parent’s abstract method. 
• But in Objective-C there is no abstract class. But in case of study the protocol in 
Objective-C is abstract class in Java. 
• You can define this protocol by using @optional and @required, method that 
declaration in @optional block like method in abstract class and method that 
declaration in @required like abstract method in abstract class.
Abstract Class (cont.) 
• You may feel something completely different for create the protocol instead of abstract 
class. 
• We use protocol to create custom delegate that allow yours object do not depend on the 
particular class. 
• Delegates are a useful tool in communicating between objects. 
• (We will talk about protocol and delegate in the next chapter.)
Polymorphism 
• Polymorphism => Poly + morphism that Poly = many and morphism = form, so it mean 
that one class can create object in many form 
• Polymorphism occur when there inheritance, it will have polymorphism automatically 
when we inherits from the super class 
• Polymorphism in objective-c occur when there are overriding method, if there isn’t 
overriding method it will use the method of the supper class. 
• We use polymorphism in form that superclass want to be the its subclass that use the 
overriding method. 
• We use polymorphism to extensible our program
Polymorphism 
Many form 
Together speak
Polymorphism 
• How to use polymorphism? 
We assume that we have a superclass ‘Person’ that method is ‘walk’ and subclass 
‘Student’ overriding method ‘walk’, because Person and Student need to walk 
Example 
objective c Java 
Person *p = [[Student alloc]init]; Person p = new Student(); 
[p walk]; p.walk(); 
Class Person create object that reference to subclass and it will call method in subclass if we 
have a overriding method in sub class, but if we don’t have a overriding method it will call 
method in superclass and it is not a complete polymorphism.
Polymorphism
Dynamic Typing and Dynamic Binding 
• In dynamic typing and dynamic binding, we create generic object to point to every other 
objects to invoke particular method. 
• In short, it is used as polymorphism. However it doesn’t mean that Polymorphism in 
Objective c must use “id”. 
• Let see an example, as we have class “Person” and class “Student” that both have the 
same method “Walk”, we will use “id” type to invoke both of student and person method.
Dynamic Typing and Dynamic Binding 
id dynamicObject; 
Person *p = [[Person alloc]init]; 
Student *s=[[Student alloc]init]; 
dynamicObject=p; 
[dynamicObject walk]; 
dynamicObject=s; 
[dynamicObject walk];
Dynamic Typing and Dynamic Binding 
• dynamicObject is id type that is a generic pointer so dynamicObject can point to both 
student (s) and Person (p) object 
• The system will know the class type of s and p object when dynamicObject point to 
them 
• And also the system know which method (walk) belong to which class
Static Typing 
• Static typing is contrast to dynamic typing. 
• We don’t use id as generic pointer 
• We use static typing to ensure our object consistency throughout program 
• And also for more readable 
id p; vs Person *p; 
• Which one do you think is more readable? id p;? Or Person *p?
Exception 
• Like java, exception in Objective-C is used to catch errors in runtime. 
• Syntax: 
@try{ 
statement(s); 
} 
@catch(NSException *exception){ 
statement(s); 
}
Thank you

Más contenido relacionado

La actualidad más candente

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsBhushan Nagaraj
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01Zafor Iqbal
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 

La actualidad más candente (20)

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
Java basic
Java basicJava basic
Java basic
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
class and objects
class and objectsclass and objects
class and objects
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 

Destacado

Sociologypresentation
SociologypresentationSociologypresentation
SociologypresentationGabby122193
 
Careers in Communications
Careers in CommunicationsCareers in Communications
Careers in CommunicationsLetterwriters
 
Permendikbud no-65-th-2013-ttg-standar-proses
Permendikbud no-65-th-2013-ttg-standar-prosesPermendikbud no-65-th-2013-ttg-standar-proses
Permendikbud no-65-th-2013-ttg-standar-prosesAlvin Cg
 
Solving the Puzzle Progress Update 2013
Solving the Puzzle Progress Update 2013Solving the Puzzle Progress Update 2013
Solving the Puzzle Progress Update 2013RobertaPembina
 
Andres cervantes
Andres cervantesAndres cervantes
Andres cervantescamilacotes
 
The 51st International Paris Air Show at Le Bourget Airport
The 51st International Paris Air Show at Le Bourget AirportThe 51st International Paris Air Show at Le Bourget Airport
The 51st International Paris Air Show at Le Bourget AirportMark Thek
 

Destacado (7)

Sociologypresentation
SociologypresentationSociologypresentation
Sociologypresentation
 
Careers in Communications
Careers in CommunicationsCareers in Communications
Careers in Communications
 
Permendikbud no-65-th-2013-ttg-standar-proses
Permendikbud no-65-th-2013-ttg-standar-prosesPermendikbud no-65-th-2013-ttg-standar-proses
Permendikbud no-65-th-2013-ttg-standar-proses
 
Reforma migratoria 2
Reforma migratoria 2Reforma migratoria 2
Reforma migratoria 2
 
Solving the Puzzle Progress Update 2013
Solving the Puzzle Progress Update 2013Solving the Puzzle Progress Update 2013
Solving the Puzzle Progress Update 2013
 
Andres cervantes
Andres cervantesAndres cervantes
Andres cervantes
 
The 51st International Paris Air Show at Le Bourget Airport
The 51st International Paris Air Show at Le Bourget AirportThe 51st International Paris Air Show at Le Bourget Airport
The 51st International Paris Air Show at Le Bourget Airport
 

Similar a Presentation 3rd

Similar a Presentation 3rd (20)

Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Objective c
Objective cObjective c
Objective c
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
C# interview
C# interviewC# interview
C# interview
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Classes2
Classes2Classes2
Classes2
 
Application package
Application packageApplication package
Application package
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
Java
JavaJava
Java
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
oops-1
oops-1oops-1
oops-1
 
Unit i
Unit iUnit i
Unit i
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 
Java notes
Java notesJava notes
Java notes
 

Presentation 3rd

  • 1. More on class, Interitance, Polymorphism Chhorn Chhaly Leang Bunrong Cheng Udam Kan Vichhai Srou Chanthorn Em Vy Seth Sambo Chea Socheat
  • 2. Content • Interface and Implement file • Multiple Arguments to Method, Local Variable, Static Variable • Self Keyword and Return Object • Inheritance • Overriding Method • Abstract Class • Polymorphism • Dynamic Typing and Dynamic Binding • Exception
  • 3. Interface and Implementation files(class)  Objective-C separated two files to manage declaration area and definition area. 1. Interface file has extension .h (header file).it is used to declare fields,properties,methods. 2. Implementation file has extension .m (execute file). It is used to implement method bodies.  In objective – C to create class we need two files .h and .m so interface file plus implementation file equal to create class in objective – C.
  • 4. Interface and Implementation files (cont.)  Interface files (.h) All fields must declare in “{ fileds }”. “{ }” is omitted when no field declaration. Methods and properties are declare outside of “{ }”.  Notice: In Objective – C we can declare fields in interface file but it recommend that should not declare here because data encapsulation. You should declare in implementation file.
  • 5. Interface and Implementation files (cont.)  Interface files (.h) example:
  • 6. Interface and Implementation files (cont.)  Implementation file(.m) Fields should declare here for data encapsulation.
  • 7. Interface and Implementation files (cont.)  Implementation file(.m) example:
  • 8. Synthesized Accessor Method  synthesized: Synthesized keyword is used to create getter and setter method in objective – C (version older than 2.0 and version 2.0).but nowadays we don’t need to use it because Xcode tool add more features that it generate setter and getter method automatically for our projects.  Syntax: @synthesize propertyname; Or @synthesize propertyname=_propertyname;  Sometime, we declared properties without fields instance of class so synthesize keyword also generate instance fields of class that begin with symbol “_”.
  • 9. Synthesized Accessor Method  Synthesized keyword example:  Both files( .m and .h) we didn’t declare field. so synthesize keyword will generate field( instance variable of class) for samename property that field beging with symbol “_”  ( _samename).
  • 10. Accessing Property  Access through normal messaging syntax: [ object setProperty:NewValue] [object property]
  • 11. Accessing Property  Access via dot syntax(Objective – C version 2.0): Object.property; Object.property=NewValue;
  • 12. Multiple Arguments to methods • In Java: void functionX(int x, int y, int z){ //statement } Object.functionX(x, y, z); //Calling function • In Objective-c: -(void) functionX:(int)x withY:(int)y, withZ:(int)z; [Object functionX:x withY:y withZ:z];
  • 13. Method without argument name • When creating the name for a method, the argument names are actually optional. For example, you can declare a method like this: -(int) set: (int) n: (int) d; • Note that, unlike in previous examples, no name is given for the second argument to the method here. This method is named set:: , and the two colons mean the method takes two arguments, even though they’re not all named. • To invoke the set:: method, you use the colons as argument delimiters, as shown here: [aFraction set:1 :3]; • It’s not good programming style to omit argument names when writing new methods because • it makes the program harder to follow and makes the purpose of the method’s actual parameters less intuitive.
  • 14. Local Variable • Local variable refers to variables located inside a block of code, a method or a function Example: - (void) fishing{ Int fish = 0; Int banana = 8; While(fish < 0){ banana = banana+1; } - } Local variables that are basic C data types have no default initial value, so you must set them to some value before using them. Local object variables in Objective-c are initialized to nil by default.
  • 15. Method Arguments • The names you use to refer to a method’s arguments are also local variables. Suppose you had a method called calculate: , defined as follows: -(void) calculate: (double) x { x *= 2; //another statement }
  • 16. The Static keyword • You can have a local variable retain its value through multiple invocations of a method by placing the keyword static in front of the variable’s declaration. Example: static int hitCount = 0; • Unlike other local variables, which are basic data types, a static variable does have an initial value of 0 , so the initialization shown previously is redundant. Furthermore, they are initialized only once when program execution begins and retain their values through successive method calls.
  • 17. Self keyword • Is a special variable in objective-c, inside instance method this variable refer to the receiver (instance) of the Message that invoke the method, while a class self indicate which class is calling. @import “A.h” @implementation A -(void)print:(NSString *)message{ NSLog(@”%@”,message) } -(void) saySomething{ [self print : @”Hello World”]; }@end Note : we can called instance method from self variable. because self variable is refer to the instance of the current class. In this example we call instance method print from self key-word inside the method saySomething() It is possible for use self instead of create the new instance method of the current class.
  • 18. Returning object • Class is also data type. Data type use precede of identifier to refer what kind of type that identifier can be accept. Data type can also use for method to refer what kind of data that method will return. -(Fraction *) add:(Fraction *)f; Note : Add:method will return a Fraction object and that it will take one as it argument as well. This method will return Fraction object value to the sender of the message with the return statement.
  • 19. Inheritance • What is inheritance?  Inheritance is a technique that a new class is derived or inherited from an existence class. • What is subclasses, based classes?  We can call subclasses as derived classes, child classes – the class that inherit from the based class.  We can call based classes as parent classes, superclass – the class that was inherited by subclasses. • Why inheritance?  Inheritance provides us many advantages such as: o Reusability – no need to write code again and again. o Expendability – extends more methods the superclass. o Overriding – we can also override the superclass methods if it doesn’t match with our problem.
  • 20. Inheritance • In Objective-C, it is allow only single inheritance not multi inheritance. • Subclasses can only take non-private properties and methods only. • In Objective-C, every classes must inherit from the root class. NSObject is the root class in Objective-C. • What is root class?  Root class is a class that doesn’t have parent at the top of it. Example: NSObject.
  • 21. Inheritance • Here is example of what our inheritance look like: #import <Foundation/Foundation.h> //SuperClass declaration and definition @interface SuperClass: NSObject{ int x; } -(void) initX; @end @implementation SuperClass -(void) initVar{ x=100; } @end @ In java: public class SuperClass extends NSObject{ public int x; public void initX(){ x=100; } }
  • 22. Inheritance • @interface SuperClass: NSObject 1 2 3 4 o 1: @inhterface – it is similar to the class keyword in java. o 2: SuperClass – our class name. o 3: “:” – extends o 4: NSObject – SuperClass
  • 23. Inheritance • Now, let create another class and extend from our SuperClass class. And we also want to add some more method for that class. #import<Foundation/Foundation.h> @interface SubClass: SuperClass -(void) printVar; @end @implementation SubClass -(void) printVar{ NSLog(@”The value of x is: %i”,x); } @end #import “SubClass.h” int main (int argc, char *argv[]){ @autoreleasepool{ SubClass *sub=[[SubClass init] alloc]; [sub initVar]; [sub printVar]; } return 0; }
  • 24. Inheritance • After seeing some examples above, we can say that:  NSObject has SuperClass as its subclass and SuperClass also has SubClass as its subclass.  Or we can say that, SubClass has SuperClass as its superclass and SuperClass has NSObject as its superclass. NSObject SuperClass SubClass subclass superclass subclass superclass
  • 25. Inheritance • The @class Directive:  This will tell compiler that you will use that class in our code.  It will not import the header file and therefore will compile a little faster. • What is the differences between @class and #import?  @class – it will tell our compiler that we will use one class. But we cannot use methods or properties from that class. Because we not include the whole “.h” header file.  #import - it will actually import the header file during compilation and is needed when we want to use the members of that class. That is how the compiler knows what properties, methods, etc can be used safely.
  • 26. Overriding Methods • Overriding is the action of replacing a method from a superclass with a more specific version of itself. • Overriding methods is the primary way by which you can customize the behavior of the classes participating in a hierarchy. • It’s like Java, the overriding method has the same name, number and type of parameters, and return type as the method it overrides.
  • 27. Overriding Methods(Cont.) Example : We have two classes, Person and Student • Person Class @interface Person : NSObject{ int age; } -(void)initAge:(int)a; @end ---------------------------- @implementation Person -(void)initAge:(int)a { age = a; } @end • Student Class @interface Student : Person //Overriding Method -(void)initAge:(int)a; -(void)displayAge; @end --------------------------- @implementation Student -(void)initAge:(int)a{ age=a; } -(void)displayAge{ NSLog(@"Your age is %i",age); } @end • Main Student * stu =[Student new]; [stu initAge:20]; [stu displayAge];
  • 28. Abstract Class • In general, abstract class is the class, which typically incomplete by itself and cannot be instantiated, but contains useful code that reduce the implementation of its subclasses. • As we know in Java we mark abstract class by the abstract keyword and all its subclass must have implement all parent’s abstract method. • But in Objective-C there is no abstract class. But in case of study the protocol in Objective-C is abstract class in Java. • You can define this protocol by using @optional and @required, method that declaration in @optional block like method in abstract class and method that declaration in @required like abstract method in abstract class.
  • 29. Abstract Class (cont.) • You may feel something completely different for create the protocol instead of abstract class. • We use protocol to create custom delegate that allow yours object do not depend on the particular class. • Delegates are a useful tool in communicating between objects. • (We will talk about protocol and delegate in the next chapter.)
  • 30. Polymorphism • Polymorphism => Poly + morphism that Poly = many and morphism = form, so it mean that one class can create object in many form • Polymorphism occur when there inheritance, it will have polymorphism automatically when we inherits from the super class • Polymorphism in objective-c occur when there are overriding method, if there isn’t overriding method it will use the method of the supper class. • We use polymorphism in form that superclass want to be the its subclass that use the overriding method. • We use polymorphism to extensible our program
  • 31. Polymorphism Many form Together speak
  • 32. Polymorphism • How to use polymorphism? We assume that we have a superclass ‘Person’ that method is ‘walk’ and subclass ‘Student’ overriding method ‘walk’, because Person and Student need to walk Example objective c Java Person *p = [[Student alloc]init]; Person p = new Student(); [p walk]; p.walk(); Class Person create object that reference to subclass and it will call method in subclass if we have a overriding method in sub class, but if we don’t have a overriding method it will call method in superclass and it is not a complete polymorphism.
  • 34. Dynamic Typing and Dynamic Binding • In dynamic typing and dynamic binding, we create generic object to point to every other objects to invoke particular method. • In short, it is used as polymorphism. However it doesn’t mean that Polymorphism in Objective c must use “id”. • Let see an example, as we have class “Person” and class “Student” that both have the same method “Walk”, we will use “id” type to invoke both of student and person method.
  • 35. Dynamic Typing and Dynamic Binding id dynamicObject; Person *p = [[Person alloc]init]; Student *s=[[Student alloc]init]; dynamicObject=p; [dynamicObject walk]; dynamicObject=s; [dynamicObject walk];
  • 36. Dynamic Typing and Dynamic Binding • dynamicObject is id type that is a generic pointer so dynamicObject can point to both student (s) and Person (p) object • The system will know the class type of s and p object when dynamicObject point to them • And also the system know which method (walk) belong to which class
  • 37. Static Typing • Static typing is contrast to dynamic typing. • We don’t use id as generic pointer • We use static typing to ensure our object consistency throughout program • And also for more readable id p; vs Person *p; • Which one do you think is more readable? id p;? Or Person *p?
  • 38. Exception • Like java, exception in Objective-C is used to catch errors in runtime. • Syntax: @try{ statement(s); } @catch(NSException *exception){ statement(s); }