OnJava8-Examples/innerclasses/LocalInnerClass.java

66 lines
1.6 KiB
Java
Raw Permalink Normal View History

2015-09-07 11:44:36 -06:00
// innerclasses/LocalInnerClass.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Holds a sequence of Objects
2015-06-15 17:47:35 -07:00
interface Counter {
int next();
}
public class LocalInnerClass {
private int count = 0;
Counter getCounter(final String name) {
// A local inner class:
class LocalCounter implements Counter {
2017-05-01 14:33:10 -06:00
LocalCounter() {
2015-06-15 17:47:35 -07:00
// Local inner class can have a constructor
2015-11-03 12:00:44 -08:00
System.out.println("LocalCounter()");
2015-06-15 17:47:35 -07:00
}
@Override public int next() {
2015-11-03 12:00:44 -08:00
System.out.print(name); // Access local final
2015-06-15 17:47:35 -07:00
return count++;
}
}
return new LocalCounter();
}
2016-01-25 18:05:55 -08:00
// Repeat, but with an anonymous inner class:
2015-06-15 17:47:35 -07:00
Counter getCounter2(final String name) {
return new Counter() {
// Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{
2015-11-03 12:00:44 -08:00
System.out.println("Counter()");
2015-06-15 17:47:35 -07:00
}
@Override public int next() {
2015-11-03 12:00:44 -08:00
System.out.print(name); // Access local final
2015-06-15 17:47:35 -07:00
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++)
2015-11-03 12:00:44 -08:00
System.out.println(c1.next());
2015-06-15 17:47:35 -07:00
for(int i = 0; i < 5; i++)
2015-11-03 12:00:44 -08:00
System.out.println(c2.next());
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
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
2015-09-07 11:44:36 -06:00
*/