Accessing the containing class of an inner class in Java

后端 未结 3 996
时光取名叫无心
时光取名叫无心 2021-01-17 09:12

This is what I\'m doing now. Is there a better way to access the super class?

public class SearchWidget {
    private void addWishlistButton() {
        fina         


        
3条回答
  •  执笔经年
    2021-01-17 09:36

    To access super of the object that contains an object of an anonymous class from that object, try, in your case SearchWidget.super


    Example:(see the third call Child.super.print())

    public class Test1 {
    public static void main(String[] args) {
        new Child().doOperation();
    }
    }
    
    class Parent {
    protected void print() {
        System.out.println("parent");
    }
    }
    
    class Child extends Parent {
    @Override
    protected void print() {
        super.print();
        System.out.println("child");
    }
    
    void doOperation() {
        new Runnable() {
            public void run() {
                print();              // prints parent child
                Child.this.print();   // prints parent child
                Child.super.print();  // prints parent
            }
        }.run();
    
    }
    }
    

提交回复
热议问题