最近学习神书《Java编程思想》,学习到第10章内部类的内容时,花了很久时间消化。现在基本搞懂了一些基本,用一份代码大致上总结了全章大部分内容。
解释说明全部在代码中用注释标识,以供理解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| package com.blackside.chapter_10;
interface Counter { int next(); }
public class TestForInnerClass { private String name = "OuterClass"; private int testCount;
private class InnerClass { private String name = "InnerClass";
public String returnInnerName() { return this.name; }
public String returnOuterName() { return TestForInnerClass.this.name; } }
public Counter[] getLocalInnerClass(final String givenName) { Counter[] counters = new Counter[2];
class LocalInnerClass implements Counter { private String name = "LocalInner"; private int number;
public LocalInnerClass(int number) {
this.number = number;
System.out.println("I am LocalInnerClass " + this.number + "."); }
@Override public int next() { System.out.print(TestForInnerClass.this.name + name + " " + givenName + " " + this.number + " output "); return testCount++; } } counters[0] = new LocalInnerClass(1); counters[1] = new LocalInnerClass(2); return counters; }
public Counter getAnonymousInner(final String givenName) { return new Counter() { private String name = "LocalAnonymousClass";
{
System.out.println("I am LocalAnonymousInnerClass."); }
@Override public int next() { System.out.print(TestForInnerClass.this.name + " " + name + " " + givenName + " output "); return testCount++; } }; }
public InnerClass getInnerClass() { return new InnerClass(); }
public static void main(String[] args) { TestForInnerClass test = new TestForInnerClass();
InnerClass innerClass = test.getInnerClass(); System.out.println(innerClass.returnInnerName()); System.out.println(innerClass.returnOuterName());
Counter[] localInner = test.getLocalInnerClass("001"); System.out.println(localInner[0].next()); System.out.println(localInner[1].next());
Counter anonymousInner = test.getAnonymousInner("002"); System.out.println(anonymousInner.next()); } }
|