ise*_*all 4 methods virtual class objective-c abstract
可能重复:
在Objective C中创建一个抽象类
在Java中,我喜欢使用抽象类来确保一堆类具有相同的基本行为,例如:
public abstract class A
{
// this method is seen from outside and will be called by the user
final public void doSomething()
{
// ... here do some logic which is obligatory, e.g. clean up something so that
// the inheriting classes did not have to bother with it
reallyDoIt();
}
// here the actual work is done
protected abstract void reallyDoIt();
}
Run Code Online (Sandbox Code Playgroud)
既然如果B类继承自A类,它只需要实现reallyDoIt().
如何在Objective C中做到这一点?它可能吗?在Objective C中它可行吗?我的意思是整个范式似乎在Objective C中有所不同,例如我从中理解的是没有办法禁止覆盖一个方法(比如Java中的'final')?
谢谢!
gio*_*shc 11
不覆盖目标c中的方法没有实际限制.你可以使用Dan Lister在他的回答中建议的协议,但这只是强制执行你的符合类来实现在该协议中声明的某个行为.
目标c中抽象类的解决方案可以是:
interface MyClass {
}
- (id) init;
- (id) init {
[NSException raise:@"Invoked abstract method" format:@"Invoked abstract method"];
return nil;
}
Run Code Online (Sandbox Code Playgroud)
这样就可以防止抽象类中的方法被调用(但是只能在运行时调用,而不像java那样可以在编译时检测到这种语法).