OnJava8-Examples/enums/cartoons/EnumImplementation.java

35 lines
987 B
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// enums/cartoons/EnumImplementation.java
2015-12-15 11:47:04 -08:00
// (c)2016 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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// An enum can implement an interface
package enums.cartoons;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.function.*;
2015-06-15 17:47:35 -07:00
enum CartoonCharacter
2015-11-03 12:00:44 -08:00
implements Supplier<CartoonCharacter> {
2015-06-15 17:47:35 -07:00
SLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB;
private Random rand = new Random(47);
@Override
2015-11-03 12:00:44 -08:00
public CartoonCharacter get() {
2015-06-15 17:47:35 -07:00
return values()[rand.nextInt(values().length)];
}
}
public class EnumImplementation {
2015-11-03 12:00:44 -08:00
public static <T> void printNext(Supplier<T> rg) {
System.out.print(rg.get() + ", ");
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
// Choose any instance:
CartoonCharacter cc = CartoonCharacter.BOB;
for(int i = 0; i < 10; i++)
printNext(cc);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
BOB, PUNCHY, BOB, SPANKY, NUTTY, PUNCHY, SLAPPY, NUTTY,
NUTTY, SLAPPY,
2015-09-07 11:44:36 -06:00
*/