泛型可以用于匿名内部类
package com.cnsuning.src;
public class Main {
public static void main(String[] args) {
Generator<Robot> g = Robot.generator;
for(int i=0;i<5;i++){
System.out.println(g.next());
}
}
}
interface Generator<T>{
public T next();
}
class Robot{
private static int count=0;
private int id=count++;
public String toString(){
return "Robot "+id;
}
public static Generator<Robot> generator = new Generator<Robot>(){
@Override
public Robot next() {
// TODO Auto-generated method stub
return new Robot();
}
};
private Robot(){
}
}
运行结果:
Robot 0
Robot 1
Robot 2
Robot 3
Robot 4