Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method from another method in abstract class with same name in real class

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.

like image 555
Mohse Taheri Avatar asked Jan 11 '15 14:01

Mohse Taheri


2 Answers

[...] but this.delete(id, true) call delete in FileGroup instead of calling delete in Controller.

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.

like image 116
aioobe Avatar answered Oct 24 '22 09:10

aioobe


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.

like image 22
Paul Boddington Avatar answered Oct 24 '22 09:10

Paul Boddington