简体   繁体   中英

Static Factory Method query

prob 1 : What is this code its a constructor or a method or else?
prob 2 : How is this return statement working (both)?
Can anyone please explain...

public class RandomIntGenerator 
{
    private final int min;
    private final int max;

    private RandomIntGenerator(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public static RandomIntGenerator between(int max, int min)    //Prob 1    
    {
        return new RandomIntGenerator(min, max);                  //Prob 2    
    }

    public static RandomIntGenerator biggerThan(int min) {
        return new RandomIntGenerator(min, Integer.MAX_VALUE);      //Prob 2    
    }

    public static RandomIntGenerator smallerThan(int max) {
        return new RandomIntGenerator(Integer.MIN_VALUE, max);
    }

    public int next() {...}      //its just a method
}

Basically they are methods which return new instances of the RandomIntGenerator class. Once you have those you can use the next() method to get random numbers.

RandomIntGenerator generator = RandomIntGenerator.between(5, 10);
int a = generator.next(); //a is now a "random" number between 5 and 10.

If the constructor was public, you could replace the first line with the line below, as they have the same effect.

RandomIntGenerator generator = new RandomIntGenerator(5, 10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM