java中匿名內(nèi)部類的匿名構(gòu)造函數(shù)是怎么用的

下面的例子說明匿名內(nèi)部類的匿名構(gòu)造函數(shù)的用法 

例2.7.2_0

interface FigureMark_to_win {
    void whoAmI();
}
public class Test {
    public static void main(String[] args) {
        FigureMark_to_win ttm = new FigureMark_to_win() {
            private String msg = "三角形";
          
            {//馬克-to-win: 匿名構(gòu)造函數(shù)
                msg = "長(zhǎng)方形";
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}


result is:
長(zhǎng)方形

結(jié)合前面的討論,內(nèi)部類訪問外邊的局部變量時(shí),此變量必須為final類型,我們給出下面例子:




例2.7.2_1:

interface FigureMark_to_win {
    void whoAmI();
}
public class Test {
    public static void main(String[] args) {
        final String out="長(zhǎng)方形";
        FigureMark_to_win ttm = new FigureMark_to_win() {
            private String msg = "三角形";
          
            {//馬克-to-win: 匿名構(gòu)造函數(shù)
                msg = out;
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}

結(jié)果:

長(zhǎng)方形




例2.7.2_2:(參考我的第一章:命令行參數(shù))

注意我運(yùn)行時(shí), 命令行參數(shù)給進(jìn)的是“長(zhǎng)方形在命令行”
interface FigureMark_to_win {
    void whoAmI();
}
public class Test {
    public static void main(final String[] args) {
        FigureMark_to_win ttm = new FigureMark_to_win() {
            private String msg = "三角形";
           
            {//馬克-to-win: 匿名構(gòu)造函數(shù)
                msg = args[0];
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}
結(jié)果:
長(zhǎng)方形在命令行




例2.7.2---本章源碼
interface FigureMark_to_win {
    void whoAmI();
}
public class Test {
    public static void main(final String[] args) {
        FigureMark_to_win ttm = new FigureMark_to_win() {
            private String msg = "三角形";
          
            {//馬克-to-win: 匿名構(gòu)造函數(shù)
                msg = "長(zhǎng)方形";
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}


result is:
長(zhǎng)方形