匿名內部類和內部類中的this


package test;

public class A extends B {
    
    public String toString() {
        return "A";
    }

    public static void main(String[] args) {
        A a = new A();
        a.say();
        
        A.AIn aa = a.new AIn();
        aa.bin();
        
    }
    
    class AIn extends BIn{
        
    }

}
package test;

public class B {
    public Thread thread;
    
    public void say() {
        //輸出A
        System.out.println(this.toString());
        // 輸入A,父類方法中使用真正子類對象用"父類.this"
        System.out.println(B.this.toString());

        say1(new I() {
            public void II() {//匿名內部類的this
                System.out.println(this);//B$1
                System.out.println(B.this);//A
//                System.out.println(A.this);  父類是訪問不到子類A的,只能寫B. 不能寫B.A的屬性,只能寫B.B的屬性,也就是給子類A對象賦值,因為訪問不到A的任何東西
                thread = Thread.currentThread();
                B.this.thread = Thread.currentThread();
            }
        });
    }

    public String toString() {
        return "B";
    }

    public void say1(I i) {
        i.II();
    }
    
    class BIn{
        public void bin() {
            B.this.thread = Thread.currentThread();
//            A.this.thread = Thread.currentThread();   父類是訪問不到子類A的,只能寫B.
            System.out.println(B.this);//A
        }
    }
}
package test;

public interface I {
    void II();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM