Java: How to call super method from inner in-place class

萝らか妹 提交于 2021-02-04 16:52:06

问题


I have base class Foo with method spam and class Bar which overrides spam. I need to call spam of base class in method of some callback object which is defined in-place:

public class Foo {
    public void spam() {
        // ...
    }
}

public class Bar extends Foo {
    @Override
    public void spam() {
        objectWhichRequireCallback(new Callback {
            @Override
            public void onCallback() {
                super.spam();
            }
        });
    }
}

This code is not working because super is related to Callback, not Bar class. Is it possible to call super method from object defined in-place?


回答1:


public class Bar extends Foo {
    @Override
    public void spam() {
        objectWhichRequireCallback(new Callback {
            @Override
            public void onCallback() {
                Bar.super.spam();
            }
        });
    }
}

EDIT : Sorry. DIdn't realize the method names are the same.




回答2:


You can create a wrapper function for this, in Bar

public class Bar...

    public void mySuperSpam(){
        super.spam();
    }



回答3:


Try this: Bar.super.spam();

Bar.this.spam(); is compiled but it will cause infinite recursion because you call the same spam() itself.



来源:https://stackoverflow.com/questions/7079600/java-how-to-call-super-method-from-inner-in-place-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!