开发者

Java Method Overriding - accessing methods in parent - is this possible?

开发者 https://www.devze.com 2023-03-18 16:38 出处:网络
Let\'s say I create an instance of a class and override one of its methods at the same time - like this

Let's say I create an instance of a class and override one of its methods at the same time - like this

MyClass fred = new MyClass() {
    @Override
    public void mymethod() {
        super.mymethod();
        //call something here
    }
};

Now let's imagine I want to call a local method which has the SAME name and SAME (lack of) parameters as my overridden method - e.g. I have

public void mymethod() {
    //my stuff in here
}
开发者_JAVA百科

How can I call that from within the overridden method (on the line //call something here)???

Is that even possible? Using

this.mymethod();  

causes an endless loop (the overriden method is simply calling itself)

Is there a way of accessing this method (other than via a static reference perhaps?)

Sorry if this is a common question - it's a hard thing to search for and the one question I found had no replies and wasn't really that well-phrased so I'm trying myself!!


I don't have a complier handy so I'm not 100% sure here, but try this:

ParentClass.this.myMethod();


An ugly, but functioning solution:

final MyOtherClass parent = this;

MyClass fred = new MyClass() {
    @Override
    public void mymethod() {
        super.mymethod();
        parent.mymethod();
    }
};

I'm struggling to see the scenario where you need to do this for naming purposes, but it's useful to know that this in the anonymous class will refer to the anonymous class, not the "parent"; so if you find the need to access the parent's method it's a useful technique.

FWIW, here's a working example.


I am not sure if I fully understood the question but my guess is that you want something like this:

public class ParentClass {
    public void mymethod() {
        ....
    }

    public void someOtherMethod() {
        MyClass fred = new MyClass() {
            @Override
            public void mymethod() {
                super.mymethod();
                //call something here
                ParentClass.this.mymethod();
            }
        }
    }
}

Note ParentClass.this.mymethod()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号