【发布时间】:2019-07-31 15:04:38
【问题描述】:
有没有办法在另一个类中使用非静态公共 int?
我希望在类中包含有用的功能和静态信息,我在不同包中的许多其他类中使用这些信息。
info.longrandom
不工作,因为它是非静态的。
package common.info
public class info {
public int veryshortrandom = (int)(Math.random() * 500 + 1001);
public int shortrandom = (int)(Math.random() * 1000 + 2001);
public int mediumrandom = (int)(Math.random() * 1500 + 3001);
public int longrandom = (int)(Math.random() * 3000 + 6001);
public int verylongrandom = (int)(Math.random() * 6000 + 1201);
}
我希望有类似的东西:
return info.longrandom
【问题讨论】:
-
首先你必须创建
info类的对象然后访问它的成员——如果你不想使用static。 -
如果它不是静态的,你可以从另一个类调用它,但使用
info的实例 -
return new info().longrandom;应该可以工作。每次也返回一个新值 -
@XtremeBaumer 确实如此,但在此处设置为
static更有意义。 -
谢谢你 XtremeBaumer,这对我来说很好用。