标签:
package com.mufeng.thetenthchapter;
interface Counter {
int next();
}
public class LocalInnerClass {
private int count = 0;
Counter getCounter(final String name) {
class LocalCounter implements Counter {
public LocalCounter() {
// TODO Auto-generated constructor stub
// Local inner class can have a constructor
System.out.println("LocalCounter()");
}
@Override
public int next() {
// TODO Auto-generated method stub
System.out.print(name);
return count++;
}
}
return new LocalCounter();
}
Counter getCounter2(final String name) {
return new Counter() {
// Anonymous inner class cannot have named constructor,only an
// instance initializer
{
System.out.println("Counter()");
}
@Override
public int next() {
// TODO Auto-generated method stub
System.out.print(name);
return count++;
}
};
}
public static void main(String[] args) {
LocalInnerClass lic = new LocalInnerClass();
Counter c1 = lic.getCounter("Local inner "),
c2 = lic.getCounter2("Anonymous inner ");
for (int i = 0; i < 5; i++) {
System.out.println(c1.next());
}
for (int i = 0; i < 5; i++) {
System.out.println(c2.next());
}
}
}
LocalCounter() Counter() Local inner 0 Local inner 1 Local inner 2 Local inner 3 Local inner 4 Anonymous inner 5 Anonymous inner 6 Anonymous inner 7 Anonymous inner 8 Anonymous inner 9
标签:
原文地址:http://blog.csdn.net/u013693649/article/details/52117572