问题1:这段代码是构造函数或方法的代码是什么? 问题2:这个退货声明如何运作(两者)? 任何人都可以解释......
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
}
答案 0 :(得分:0)
基本上它们是返回RandomIntGenerator
类的新实例的方法。完成后,您可以使用next()
方法获取随机数。
RandomIntGenerator generator = RandomIntGenerator.between(5, 10);
int a = generator.next(); //a is now a "random" number between 5 and 10.
如果构造函数是公共的,您可以用下面的行替换第一行,因为它们具有相同的效果。
RandomIntGenerator generator = new RandomIntGenerator(5, 10);