繁体   English   中英

有没有办法从另一个文件中声明私有 object?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM