[英]Is there a way to declare a private object from another file?
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
好吧,我真的找不到用语言表达的好方法。 有没有办法在公共 class 中声明所有内容,但在不知道所有对象是什么的情况下在另一个文件/类中私下声明? 这是一个例子。
SetOfThings.java
public class SetOfThings {
// For the sake of the question, say these can change
// from time to time
public int someNumber = 1;
public string someString = "Java is kinda challenging sometimes...";
public Joystick example = new Joystick(someNumber);
}
SomeOtherFile.java
public class SomeOtherFile {
/** Some way to recreate all the public objects from
* SetOfThings with the same values, but private
* (perhaps final, too?) and without having to
* know what all the objects in SetOfThings are.
*/
}
我已经四处搜索,但正如我所说,我无法弄清楚如何在不过于具体的情况下用它来表达。 目前,我必须编辑每个文件来更新我正在调用的单独使用的内容。
你可以做的是在SomeOtherFile.java
的构造函数中添加一个私有变量SetOfThings things;
你的代码看起来像这样
SetOfThings.java
public class SetOfThings {
// For the sake of the question, say these can change
// from time to time
public int someNumber = 1;
public string someString = "Java is kinda challenging sometimes...";
public Joystick example = new Joystick(someNumber);
}
SomeOtherFile.java
public class SomeOtherFile {
private SetOfThings setOfThings; //this is so you can access all the SetOfThings variables
public SomeOtherFile(SetOfThings things){
this.setOfThings=things //attribute things to the private variable
}
}
像这样,您可以访问SomeOtherFile.java
中的SetOfThings.java
。 如果您的值没有改变,您还可以选择在SomeOtherFile
中简单地声明一个SetOfThing
object
SetOfThing myObjectInOtherClass=new SetOfThing();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.