Three Characteristics of object-oriented encapsulation, inheritance, and Polymorphism
Encapsulation: Hiding internal implementations and stabilizing external interfaces.
Encapsulation is to define the class definition property definition method.
Property encapsulates the setter get Method
@ Property (nonatomic, retain) nsstring * Name, * sex;
Class encapsulates instance variables and Methods
. H file
# Import <Foundation/Foundation. h>
@ Interface person: nsobject
{
Nsstring * _ name;
Nsstring * _ sex;
Int _ age;
}
@ Property (nonatomic, retain) nsstring * Name, * sex;
@ Property (nonatomic, assign) int age;
-(ID) initwithname :( nsstring *) Name sex :( nsstring *) sex age :( INT) age;
-(Person *) work;
@ End
. M file
# Import "person. H"
@ Implementation person
@ Synthesize name = _ name, sex = _ sex, age = _ age;
-(ID) initwithname :( nsstring *) Name sex :( nsstring *) sex age :( INT) Age
{
Self = [Super init];
If (Self ){
Self. Name = Name;
Self. Sex = sex;
Self. Age = age;
}
Return self;
}
-(Person *) Work
{
Nslog (@ "% @ working", self. Name );
Return 0;
}
@ End
Inheritance: Child classes can directly reuse members in the parent class. Child classes inherit the declaration of all methods of the parent class and implement non-private instance variables and protocols.
Inheritance is to declare in. H that inheritance has a single and pass-through inheritance, that is, the common part of code optimization is handed over to the parent class.
# Import "person. H"
@ Interface worker: person // subclass: parent class
@ End
# Import "person. H"
@ Interface King: person
@ End
Inheritance in OC: Single-core (one sub-class can only have one super class)
Passed (a-> B-> C A-> C)
Polymorphism: different objects have different responses to the same message. sub-classes can override the parent class method.
Polymorphism means that the parameter or returned value of the method can be input or returned as a parent type.
Worker * worker = [[Worker alloc] init];
Worker. Name = @ "worker ";
[Worker work];
King * King = [[King alloc] init];
King. Name = @ "King ";
[King work];