java編程思想3中的實例(AnonymousConstructor.java)
# // Creating a constructor for an anonymous inner class.
# // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
# // www.BruceEckel.com. See copyright notice in CopyRight.txt.
# import com.bruceeckel.simpletest.*;
#
//其間認識到了以前理解上的 錯誤:抽象類是可以有構(gòu)造函數(shù)的,并且僅僅是抽象類中的抽象方法不能有方法體
//在AnonymousConstructor類中定義內(nèi)部類時,依然調(diào)用Base類中的構(gòu)造函數(shù)
# abstract class Base {
# public Base(int i) { //匿名內(nèi)部類是引用的外部定義的對象,編譯器會要求其參數(shù)引用是final型(而本例中在getBase(int i)方法中的i不是final類型,是因為i沒有在外部類base中使用)
# System.out.println("Base constructor, i = " + i);
# }
# public abstract void f();
# }
#
# public class AnonymousConstructor {
# private static Test monitor = new Test();
# public static Base getBase(int i) { //定義在靜態(tài)方法中的內(nèi)部類----匿名內(nèi)部類---return new Base(i)類似于class Base{ Base(i)...的聲明
# return new Base(i) {
# {
# System.out.println("Inside instance initializer");
# }
# public void f() {
# System.out.println("In anonymous f()");
# }
# }; //此處有個分號,表明表達式的結(jié)束
# }
# public static void main(String[] args) {
# Base base = getBase(47);
# base.f();
# monitor.expect(new String[] {
# "Base constructor, i = 47",
# "Inside instance initializer",
# "In anonymous f()"
# });
# }
# } ///:~
# // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
# // www.BruceEckel.com. See copyright notice in CopyRight.txt.
# import com.bruceeckel.simpletest.*;
#
//其間認識到了以前理解上的 錯誤:抽象類是可以有構(gòu)造函數(shù)的,并且僅僅是抽象類中的抽象方法不能有方法體
//在AnonymousConstructor類中定義內(nèi)部類時,依然調(diào)用Base類中的構(gòu)造函數(shù)
# abstract class Base {
# public Base(int i) { //匿名內(nèi)部類是引用的外部定義的對象,編譯器會要求其參數(shù)引用是final型(而本例中在getBase(int i)方法中的i不是final類型,是因為i沒有在外部類base中使用)
# System.out.println("Base constructor, i = " + i);
# }
# public abstract void f();
# }
#
# public class AnonymousConstructor {
# private static Test monitor = new Test();
# public static Base getBase(int i) { //定義在靜態(tài)方法中的內(nèi)部類----匿名內(nèi)部類---return new Base(i)類似于class Base{ Base(i)...的聲明
# return new Base(i) {
# {
# System.out.println("Inside instance initializer");
# }
# public void f() {
# System.out.println("In anonymous f()");
# }
# }; //此處有個分號,表明表達式的結(jié)束
# }
# public static void main(String[] args) {
# Base base = getBase(47);
# base.f();
# monitor.expect(new String[] {
# "Base constructor, i = 47",
# "Inside instance initializer",
# "In anonymous f()"
# });
# }
# } ///:~