[英]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.