1. 程式人生 > >【WIP】對象的類型與動態結合

【WIP】對象的類型與動態結合

this center 變量 ogr 改變 inter text bool class

創建: 2018/01/21

動態結合(多態)
動態結合

呼出同一個方法,根據呼出方不同執行的處理也不同

//---------------------------------------------------------------------
//                           類型定義
//---------------------------------------------------------------------
//動態結合與多態
@interface S4_A : NSObject {
    
}
- (void)getLocationOfHierarchy;
- (void)getLocationOfHierarchy:(BOOL)isneedHello; @end @interface S4_B : S4_A { } - (void)getLocationOfHierarchy; //重載 - (void)getLocationOfHierarchy:(BOOL)isneedHello; //重載 @end //--------------------------------------------------------------------- // 類定義 //---------------------------------------------------------------------
//動態結合與多態 @implementation S4_A - (void)getLocationOfHierarchy { puts("this is A"); } - (void)getLocationOfHierarchy:(BOOL)isneedHello { if (isneedHello) { puts("hello, this is A"); } else { puts("need no hello, this is A"); } } @end @implementation S4_B - (void)getLocationOfHierarchy { puts(
"this is B"); } - (void)getLocationOfHierarchy:(BOOL)isneedHello { if (isneedHello) { puts("hello, this is B"); } else { puts("need no hello, this is B"); } } @end //--------------------------------------------------------------------- // 測試函數 //--------------------------------------------------------------------- void S4Tester(void) { puts("-----------------------------------------"); puts(" S4"); puts("-----------------------------------------"); id aTemp = [[S4_A alloc] init]; [aTemp getLocationOfHierarchy]; [aTemp getLocationOfHierarchy:NO]; [aTemp getLocationOfHierarchy:YES]; id bTemp = [[S4_B alloc] init]; [bTemp getLocationOfHierarchy]; [bTemp getLocationOfHierarchy:NO]; [bTemp getLocationOfHierarchy:YES]; }

運行結果

-----------------------------------------
                  S4
-----------------------------------------
this is A
need no hello, this is A
hello, this is A
this is B
need no hello, this is B
hello, this is B
Program ended with exit code: 0

多態

多態就是動態結合

優點: 不用對每一個具體對象改變現有代碼 p60

數據類型與類
編程的類型聲明

實例變量的封裝

類對象 (class object)

【WIP】對象的類型與動態結合