简体   繁体   English

从实际类中具有相同名称的抽象类中的另一个方法调用方法

[英]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 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 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. super.delete调用Controller.deletethis.delete(id, true)调用deleteFileGroup ,而不是调用deleteController ,这是造成递归无限循环和堆栈溢出。

[...] but this.delete(id, true) call delete in FileGroup instead of calling delete in Controller . [...]但this.delete(id, true)调用删除FileGroup ,而不是调用删除Controller

Yes, all methods are virtual in Java, and there's no way to avoid that. 是的,所有方法都是Java虚拟的,没有办法避免这种情况。 You can however work around this by creating a (non overridden) helper method in Controller as follows: 但是,您可以通过在Controller创建(非重写)辅助方法来解决此问题,如下所示:

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. 通过这样做,您可以避免让Controller.delete委托对子类的调用。

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: 如果您只是尝试在FileGroup delete方法delete(id, true)Controller调用方法delete(id, true)而不会导致堆栈溢出,您可以这样做:

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. 如果你的问题是如何使一个参数delete的方法Controller调用两个参数delete的方法Controller ,而不是在版本FileGroup ,得到的答案是,你应该使用@ aioobe的helper方法解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM