Chapter 19 - Exercise 2

(2) Instead of implementing an interface, make next( ) a static method. What are the benefits and drawbacks of this approach?


用next()不用创建实例,用起来更方便了。缺点是面向Generator接口的方法要受到影响。



package com.ciaoshen.thinkinjava.chapter19;
import java.util.*;

enum CartoonCharacter{
    SLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB;

    private static Random rand=new Random();

    public static CartoonCharacter next(){
        return values()[rand.nextInt(values().length)];
    }
}

public class Exercise2{ 
    public static void main(String[] args){
        for(int i=0;i<10;i++){
            System.out.println(CartoonCharacter.next());
        }
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.