我问这个问题是为了看看我对面向对象的工作原理的理解是否正确。假设我有一个抽象父类(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/