ios - 面向对象编程的正确概念

标签 ios objective-c class polymorphism

我问这个问题是为了看看我对面向对象的工作原理的理解是否正确。假设我有一个抽象父类(super class),它有几个方法,所有方法都有某种实现。

@interface SuperClass : UIViewController
- (void)methodOne;

// Other public stuff


@end

.......

@implementation SuperClass

- (void)methodOne
{
    //some implementation
}

- (someObject *)objectMethod
{
     //more implementation
}

@end

然后如果我正在实现它的一个子类:

@interface SubClass : SuperClass

@end

.......

@implementation SubClass

- (void)methodOne
{
    // override method implementation code
}

@end

那么从上面的例子来看,如果我创建一个 View Controller ,它是一个 SubClass 的类,它实际上会创建一个 SubClass 对象并自动添加所有 SuperClass 方法的实现吗?我的想法是,当预处理器运行时,它是否采用任何未在子类中被覆盖的方法,并将父类(super class)代码方法放入该类中供其使用?在本例中,我只覆盖了父类(super class)中的“methodOne”方法,并单独保留了“objectMethod”方法。这是否意味着我的子类将利用新的重写“methodOne”实现并使用父类(super class)的“objectMethod”实现?

非常感谢!如果我需要澄清一些事情,请告诉我。

最佳答案

如果您在 SubClass 实现中重新定义 methodOne,SubClass 的实例将使用重新定义的实现。如果没有重新定义 SubClass 实现,它将查找 SuperClass 的实现以进行定义。这个过程递归地继续通过更高的父类(super class),直到它找到一个定义。

如果你想稍微修改子类中的定义,你可以这样做:

-(void) methodOne{
    // Some code to add before SuperClass's implementation is called
    ....

    // Call SuperClass's implementation
    [super methodOne];

    // Some code to add after SuperClass's implementation is called
    ...
}

关于ios - 面向对象编程的正确概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18263120/

相关文章:

ios - 调用了drawRect,但运行时其中的代码没有被执行?

iOS GL ES 2 应用程序在设备上崩溃但在模拟器上不崩溃

ios - 如何在清晰且不同的 uiview 可以处理它们时忽略最顶层 uiview 中的触摸事件

objective-c - 放松到 swift 或 Objective-C 中的另一个分支

objective-c - NSTextView复制粘贴问题

java - 用一种方法创建一个类是否合适?

ios - UIStackView 重置其中按钮的属性

ios - CABasicAnimation 起源于右上角而不是中心

c++ - 比较存储在 vector 中的类对象的私有(private)成员变量 - C++

java - 当我想从可点击的 ListView 中打开另一个类时应用程序停止