欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OC语言day04-09构造方法练习

程序员文章站 2024-01-14 22:47:40
...

pragma mark 构造方法练习

pragma mark 概念

pragma mark 代码

#import <Foundation/Foundation.h>
#pragma mark 类
#import "Person.h"
#import "Student.h"
#pragma mark main函数
int main(int argc, const char * argv[])
{
#warning 让学生继承人类,要求学生对象初始化之后,年龄是10, 学号是1, 怎么办?
    
//    Person *p = [[Person alloc]init];
//    NSLog(@"P2 = %@",p);
//    Person *p1 = [[Person alloc]init];
//    NSLog(@"P1 = %@",p1);
    
    Student *stu = [[Student alloc]init];
    NSLog(@"%@",stu);
    
    Student *stu1 = [[Student alloc]init];
    NSLog(@"%@",stu1);

    return 0;
}

Person.h //人类 (父类)
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
@end
Person.m
#import "Person.h"

@implementation Person

- (instancetype)init
{
    if (self = [super init]) {
        // 如果父类 不等于空
        // 初始化 子类
        _age = 10;
    }
    return self;
}


- (NSString *)description
{
    return [NSString stringWithFormat:@"age = %i",_age];
}
@end

Student.h // 学生类 (子类)
#import "Person.h"
@interface Student : Person

@property int no; // 学号
@end
Student.m
#import "Student.h"

@implementation Student

- (instancetype)init
{
    if (self = [super init]) {
//        [self setAge:10];
        _no = 10;
    }
    return self;
}


- (NSString *)description
{
    return [NSString stringWithFormat:@"age = %i, no = %i",[self age],[self no]];
}
@end