Java: calling outer class method in anonymous inner class

后端 未结 1 1103
感情败类
感情败类 2020-12-01 08:01

Recently, I ran into a mysterious problem in an android project, which I described here. I somehow solved the problem, but still don\'t know the exact reason behind it.

相关标签:
1条回答
  • The latter is more explicit and will allow you to call the outer class method if one exists in the inner class with the same name.

    class OuterClass {
        void foo() { System.out.println("Outer foo"); }
    
        View.OnClickListener mListener1 = new View.OnClickListener() {
            void foo() { System.out.println("Inner foo"); }
    
            @Override public void onClick(View view) {
                foo(); //Calls inner foo
                OuterClass.this.foo(); //Calls outer foo
            }
        }
    
        View.OnClickListener mListener2 = new View.OnClickListener() {
            @Override public void onClick(View view) {
                foo(); //Calls outer foo
                OuterClass.this.foo(); //Calls outer foo
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题