让构造函数访问静态变量
现在我有两个 .java 文件。
Main.java:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger();
}
和 NeedInteger.java
public class NeedInteger {
System.out.println(integer);
}
这当然非常简化,但是有什么方法可以实现这一点吗?
Right now I have two .java files.
The Main.java:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger();
}
and the NeedInteger.java
public class NeedInteger {
System.out.println(integer);
}
This is of course very simplified, but is there any way I can accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正如许多人回答的那样,正确的方法是将值传递给新类的构造函数。
如果由于某种原因你不能这样做,那么你可以在 Main 中使用公共静态访问器方法来访问该值(这比仅仅将字段设为公共稍微好一些)。
例如
As many have answered, the correct method is to pass the value in to the constructor of the new class.
If for some reason you cannot do that, then you can use a public static accessor method in Main to access the value (this would be slightly better than just making the field public).
E.g.
向
NeedInteger
添加一个构造函数(如果您还需要存储它,还可以添加一个成员):然后在创建实例时传递您的值:
Add a constructor to
NeedInteger
(and optionally a member if you need to also store it):Then pass your value when you create the instance:
你将不得不做一些糟糕的 juju 动作(例如使用全局变量)或将其传递给构造函数。
注意:你的
里面没有方法。我建议将所有这些重写为:
如果您确实希望在构建上完成工作。
编辑:根据您上面的评论。
相反,让类的结构如下:
这没有真正的额外开销,因为不会传递实际的数组,而只会传递对其的引用。您可能希望将数组设置为
final
或其他值,以避免在NeedStringArray
构造函数中对其进行编辑。You would have to do some bad juju moves (like using a global variable) or pass it to the constructor.
NOTE: your
has no method in it. I would recommend all this to be rewritten as such:
If you really want the work to be done on construction.
EDIT: From your comment above.
Instead, have the class structured so:
That has no real additional overhead, since the actual array will not be passed, but only a reference to it. You WILL likely want to set the array to be
final
or something, to avoid it being edited in theNeedStringArray
constructors.整数是私有的,因此它不能被 NeedInteger 访问。您必须将其公开或使用 setter 或 getter,并且您需要使用 Main.integer 因为它是静态的。
一般来说,你在构造函数中设置。
integer is private, so it cannot be accessed by NeedInteger. you'll have to make it public or use a setter or getter and you'll need to use Main.integer since it's static.
Generally, you set in the Constructor.
将变量传递给类构造函数。
数组引用就是一个引用。
或者您可以传入类本身,或使用静态(meh)。
Pass in the variable to the class constructor.
An array reference would be just that--a reference.
Or you could pass in the class itself, or use a static (meh).
根据您的评论,我想说您可以将数组托管在 singleton
或者正如其他人建议的那样,让第二个类接受构造函数中对数组的引用。然后,您可以使用依赖注入框架(例如 Guice)把它们连接起来
Per your comment I'd say you can either host your array in a singleton
or as others suggested have the second class accept the reference to the array in the constructor. You can then use Dependency Injection framework (e.g. Guice) to get wire them up