【问题标题】:Is there a way to call a public int from another class?有没有办法从另一个类调用公共 int ?
【发布时间】: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,这对我来说很好用。

标签: java int public


【解决方案1】:

您只能使用类名访问类的成员,其中只有成员是静态的。由于静态成员是在全局内存中声明的,因此与仅在该类中本地存在的非静态成员不同。否则你总是需要创建实例。

【讨论】:

    【解决方案2】:

    您将需要制作一个 Getter。有两种方法: 通过执行创建类的新实例 1:

    Info info = new Info();
    

    然后通过以下方式获取 int:

    int i = info.veryshortrandom;
    

    return info.veryshortrandom;
    

    2。 使其成为静态:|

    祝你好运! - 蒂博

    【讨论】:

      【解决方案3】:

      非静态属性绑定到实例。不创建实例怎么获取?!

      【讨论】:

        【解决方案4】:

        return new info().longrandom;

        – XtremeBaumer

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-05
          • 2022-07-08
          • 2011-12-11
          • 1970-01-01
          • 1970-01-01
          • 2021-11-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多