Jakub Folejtar
Jakub Folejtar

Reputation: 350

Calling another method within method with the same name in Java

I am trying to call method which I have created long before I found out that interface I am using for another stuff need me to call its predefined method, which is the same name of the method I want to call inside. Example:

public void onClick(View v) {
    //doSomething
}
public void method() {
    Button btn = new Button(this);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //here I want to call the top onClick method
        }
    });
}

Are you guys able to help me how can I use the top method, not recursively the inside one? Thx in advance. JF

Upvotes: 1

Views: 253

Answers (2)

Guillaume Barré
Guillaume Barré

Reputation: 4228

The syntax to use is OuterClass.this.methodName();

For example if the outer class is A you need to call A.this.onClick();

interface IOnClick {
    public void onClick();
}

class A {
    public void onClick(){
    }

    public void test(){
        IOnClick ic = new IOnClick(){
            public void onClick(){
                A.this.onClick();
            }
        };
    }
}

Upvotes: 1

Egor
Egor

Reputation: 40228

The syntax would be:

<enclosing-class>.this.onClick();

so if you're say in MainActivity, then:

MainActivity.this.onClick();

Upvotes: 3

Related Questions