你知道在Objective C中如何进行继承的使用吗?

我想学习Objective C中的继承使用方法。我想知道如何在Objective C中创建一个子类并继承父类的方法和属性,以及如何在子类中添加自己的方法和属性。我也想了解Objective C中的多重继承和接口的实现方式。如果有相关的代码示例或者指引,那就更好了。谢谢!

提问时间:2023-07-13 02:01:39 编辑时间:2023-07-13 02:01:41 提问者: 独行侠客
  • Dragonfly_Dancer
    7

    在Objective C中,继承使用关键字“:”,子类可以继承父类的所有方法和属性,同时子类可以添加自己的方法和属性。使用继承时可以用super关键字去调用父类的方法。多重继承在Objective C中不被支持,但可以通过协议来实现类似接口的功能。以下是一个简单的代码示例:

    // 父类 @interface Animal : NSObject

    @property (nonatomic, strong) NSString *name;

    • (void)sayHello;

    @end

    @implementation Animal

    • (void)sayHello { NSLog(@"Hello, I'm %@.", self.name);

    }

    @end

    // 子类 @interface Dog : Animal

    @property (nonatomic, strong) NSString *breed;

    • (void)shakeTail;

    @end

    @implementation Dog

    • (void)shakeTail { NSLog(@"%@ is shaking tail.", self.name);

    }

    @end

    //使用示例 Dog *dog = [[Dog alloc] init]; dog.name = @"Lucy"; dog.breed = @"Golden Retriever"; [dog sayHello]; // 输出: Hello, I'm Lucy. [dog shakeTail]; // 输出: Lucy is shaking tail.

    回答时间:2023-07-13 02:01:45