Upload
gl-finance-plc
View
110
Download
0
Embed Size (px)
Citation preview
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
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
1 2 3 4
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
subclass superclass
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
PolymorphismMany 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