oop - In Java, doubts about anonymous inner classes calling external class methods
漂亮男人
漂亮男人 2017-05-17 10:07:37
0
1
869

Today I learned about inner classes and learned that inner classes can hold this of outer classes, so that OuterClass.this.medthod() can be used in inner classes to reference the corresponding outer class methods. But I wrote the code and it can run. However, I don't understand the calling logic very well. I hope you can enlighten me!

public class test {
        public void report(){
            System.out.println("I'm invoked!");
        }
        public void perform(){
            new Speaker().handleAction(new Action(){
                @Override
                public void action() {
                    report();//???为什么能调用report??
                }
                
            });
        }
        public static void main(String[] args) {
            new test().perform();//测试代码
        }
        
    }
    class Speaker{
        void handleAction(Action act){
            act.action();
        }
    }
    interface Action{
        void action();
    }

The design is like this. The test object calls the perform method, which creates a new Speaker anonymous class object. The object calls its handleAction method. The parameter of this method is an Action interface, and the interface needs to override the action abstract method. I used the report method belonging to test. The output is normal.

Then I want to know, there is a local object of an anonymous class in the method of the test object, and the local object parameter is an anonymous class that implements the interface. Why can report be called in this anonymous class? Does it hold the test.this pointer?
My understanding is that new Speaker().handleAction(new Action(){....The implementation logic here has nothing to do with test.this, and there is no need to hold test. this???

漂亮男人
漂亮男人

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!