Reputation: 8242
Class parent {
protected void myMethod() {
if(someCodition) {
//return this as well as child's myMethod.
}
}
Class child extends Parent {
@override
protected void myMethod() {
super.myMethod();
//code below this line should not execute if someCondition.
//want parent to handle all this
}
}
Please don't suggest to take some boolean flag kind of thing in parent class and check it in child. actually child class will be used by other developers and i dont want them to take care about any such condition, so want to exit from parent itself.
I am fully aware that it is violation of Abstraction principle of oops, but its my need to violate .
Updating
PS: to call myMethod() is not in either child or parent's control , so can not create a separate method as mentioned in one answer . actually its and API method, so system will execute it automatically as per need, and i can not stop to call it.
Upvotes: 0
Views: 989
Reputation: 178441
You are probably looking for template method pattern [or some variation of it]
The user will override the protected method myTemplateMethod()
, and myMethod()
will not be overriden.
myMethod()
will invoke super.myMethod()
[it was not overriden so actually the super will be invoked immidiately], and the super will invoke [if conditions are met] myTemplateMethod()
Something along the lines of [pseudo code]:
abstract Class parent {
protected abstract void myTemplateMethod();
protected final void myMethod() {
if(someCodition) {
myTemplateMethod();
}
}
Class child extends Parent {
@override
protected void myTemplateMethod() {
//code that will be invoked only if someCodition is met
}
}
Upvotes: 3