OnJava8-Examples/enums/cartoons/EnumImplementation.java

38 lines
1019 B
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// enums/cartoons/EnumImplementation.java
2020-10-07 13:35:40 -06:00
// (c)2020 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.
2015-06-15 17:47:35 -07:00
// An enum can implement an interface
2016-07-28 12:48:23 -06:00
// {java enums.cartoons.EnumImplementation}
2015-06-15 17:47:35 -07:00
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> {
2017-01-20 21:30:44 -08:00
SLAPPY, SPANKY, PUNCHY,
SILLY, BOUNCY, NUTTY, BOB;
private Random rand =
new Random(47);
2015-06-15 17:47:35 -07:00
@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:
BOB, PUNCHY, BOB, SPANKY, NUTTY, PUNCHY, SLAPPY, NUTTY,
NUTTY, SLAPPY,
2015-09-07 11:44:36 -06:00
*/