从抽象类中的另一个方法调用与实际类中同名的方法 [英] Call method from another method in abstract class with same name in real class

查看:44
本文介绍了从抽象类中的另一个方法调用与实际类中同名的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类和一个扩展它的类,我在两个类中有一个同名的方法.我想在抽象类的另一个方法中调用抽象类中的方法.

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.

控制器.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
    }
}

文件组.java

public class FileGroup extends Controller {

    public Result delete(Long id, boolean central) {
        // do something
        return super.delete(id);
    }
}

super.delete 调用 Controller.deletethis.delete(id, true) 调用 deleteFileGroup 而不是在 Controller 中调用 delete 这会导致递归无限循环和堆栈溢出.

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.

推荐答案

[...] 但 this.delete(id, true)FileGroup 中调用 delete 而不是在 Controller 中调用 delete.

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

是的,Java 中的所有方法都是虚拟的,并且无法避免这种情况.但是,您可以通过在 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);
    }
}

这样做可以避免 Controller.delete 将调用委托给子类.

By doing this you avoid having Controller.delete delegate the call to the subclass.

这篇关于从抽象类中的另一个方法调用与实际类中同名的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆