I have an abstract class and one class that extend it, I have a method with same name in both class. I want to call the method in abstract class in another method of abstract class.
Controller.java
public abstract class Controller {
public Result delete(Long id) {
return this.delete(id, true);
}
public Result delete(Long id, boolean useTransaction) {
// do something and return result
}
}
FileGroup.java
public class FileGroup extends Controller {
public Result delete(Long id, boolean central) {
// do something
return super.delete(id);
}
}
super.delete
call Controller.delete
but this.delete(id, true)
call delete
in FileGroup
instead of calling delete
in Controller
which is causing recursive infinite loop and stack overflows.
[...] but
this.delete(id, true)
call delete inFileGroup
instead of calling delete inController
.
Yes, all methods are virtual in Java, and there's no way to avoid that. You can however work around this by creating a (non overridden) helper method in Controller
as follows:
public abstract class Controller {
private Result deleteHelper(Long id, boolean useTransaction) {
// do something and return result
}
public Result delete(Long id) {
return deleteHelper(id, true);
}
public Result delete(Long id, boolean useTransaction) {
return deleteHelper(id, useTransaction);
}
}
By doing this you avoid having Controller.delete
delegate the call to the subclass.