85,类对象的应用场景

来源:互联网 发布:手机mac怎么改 编辑:程序博客网 时间:2024/05/24 00:29

#import <Foundation/Foundation.h>


@interface Person : NSObject


-(void)test1;

+(void)print;

+(id)productObject:(Class)c;


@end


@implementation Person


-(void)test1{

    NSLog(@"对象方法:Person");

}


+(void)print{

    NSLog(@"类方法:Person");

}

+(id)productObject:(Class)c{

    id instance = [[c alloc] init];

    return instance;

}


@end


@interface Student : Person


@end


@implementation Student


-(void)test1{

    NSLog(@"Student");

}


@end


@interface Doctor : Person


@end


@implementation Doctor


-(void)test1{

    NSLog(@"Doctor");

}


@end


int main(int argc,const char * argv[]) {

    @autoreleasepool {

        //1,获取类对象

        //[类名 class][实例对象 class]

        Person *person1 = [[Personalloc]init];

        Person *person2 = [[Personalloc]init];

        //一个类在内存中,只有一个类对象

        Class c1 = [person1 class];

        Class c2 = [person2 class];

        Class c3 = [Person class];

        NSLog(@"c1 = %p,c2 = %p,c3 = %p",c1,c2,c3);

        

        //2,类对象的应用场景

        //2.1,用于创建实例对象

        Person *p3 = [[c1 alloc] init];

        [p3 test1];

        //2.2,用于调用方法

        [c1 print];

        [Person print];

        

        //注:向方法传入不同类对象,生成不同的实例对象

        id instance1 = [PersonproductObject:[Studentclass]];

        [instance1 test1];

        id instance2 = [PersonproductObject:[Doctorclass]];

        [instance2 test1];

        

    }

    return 0;

}

//2015-12-12 11:19:03.336 9,类对象的应用场景[1321:71276] c1 = 0x1000013d0,c2 = 0x1000013d0,c3 = 0x1000013d0

//2015-12-12 11:19:03.337 9,类对象的应用场景[1321:71276]对象方法:Person

//2015-12-12 11:19:03.337 9,类对象的应用场景[1321:71276]类方法:Person

//2015-12-12 11:19:03.337 9,类对象的应用场景[1321:71276]类方法:Person

//2015-12-12 11:19:03.337 9,类对象的应用场景[1321:71276] Student

//2015-12-12 11:19:03.337 9,类对象的应用场景[1321:71276] Doctor

//Program ended with exit code: 0



0 0
原创粉丝点击