Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force child classes to override method

Tags:

How can I make it so that any class that inherits from my base class is forced to override a specific method? I don't want to use a protocol, because that wouldn't make this behavior automated.

@interface MyBaseClass : NSObject  { }  - (void)performAnAction;  @end  @implementation MyBaseClass  - (void)performAnAction {     @throw([NSException exceptionWith...]); }  @end 
like image 540
aryaxt Avatar asked Dec 06 '10 22:12

aryaxt


People also ask

How do you force a subclass to override a method?

Just declare the method as abstract in the base class. All children classes will then be forced to implement it. Alternatively you could also use an interface instead of a concrete class, which is simply an agreement that the methods defined will be implemented.

Can child classes access parent methods?

It has all of the instance variables. The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.

Is it necessary to override all methods of parent class?

You must override your method from parent class only of you want to override super class. But you must override every methodsfrom Iterface when you implement it by some of your class.

Can child class override the properties of parent class in Python?

If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.


1 Answers

How exactly do you mean, force them to override it? If you simply implement the parent method like so:

- (void)performAction {     NSAssert(NO, @"The method %@ in %@ must be overridden.",          NSStringFromSelector(_cmd), NSStringFromClass([self class])); } 

then it'll throw an exception at runtime if the child class fails to override it. Unfortunately there is no way to enforce this at compile-time.

like image 135
Lily Ballard Avatar answered Nov 23 '22 21:11

Lily Ballard