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.
It's not entirely clear what your question is. If you are just trying to make the method delete
in FileGroup
call the method delete(id, true)
in Controller
without causing a stack overflow, you can just do this:
public class FileGroup extends Controller {
public Result delete(Long id, boolean central) {
// do something
return super.delete(id, true);
}
}
If your question is how to make the one-argument delete
method in Controller
call the two-argument delete
method in Controller
rather than the version in FileGroup
, the answer is that you should use @aioobe's helper method solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With