java中匿名内部类的匿名构造函数是怎么用的

下面的例子说明匿名内部类的匿名构造函数的用法 

例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: 匿名构造函数
                msg = "长方形";
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}


result is:
长方形

结合前面的讨论,内部类访问外边的局部变量时,此变量必须为final类型,我们给出下面例子:




例2.7.2_1:

interface FigureMark_to_win {
    void whoAmI();
}
public class Test {
    public static void main(String[] args) {
        final String out="长方形";
        FigureMark_to_win ttm = new FigureMark_to_win() {
            private String msg = "三角形";
          
            {//马克-to-win: 匿名构造函数
                msg = out;
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}

结果:

长方形




例2.7.2_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: 匿名构造函数
                msg = args[0];
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}
结果:
长方形在命令行




例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: 匿名构造函数
                msg = "长方形";
            }
            public void whoAmI() {
                System.out.println(msg);
            }
        };
        ttm.whoAmI();
    }
}


result is:
长方形