我有一些代码正在利用从一个类到另一个类的变量,我使用getter和setter并且我在更改类之前我检查了setClassName()它是否正常工作但是我无法从其他类正确访问它,它return's null。
http://pastebin.com/6AP4c6ii - CLASS A.
http://pastebin.com/QCnWDnYs - CLASS B.
有更多的代码,但它相对凌乱和长,这是一个菜鸟,我正在努力改进我的编码,这只是一个小项目。
任何帮助赞赏。
I have some code that is utilising a variable from one class to another, I am using getters and setters and I checked that when i setClassName() before changing class that it works but i can't acces it properly from the other class, it return's null.
http://pastebin.com/6AP4c6ii -- CLASS A
http://pastebin.com/QCnWDnYs -- CLASS B
There is more code but it's relatively messy and long, im a noob to this and am working on ways to improve my coding and this is just a little project.
Any help appreciated.
最满意答案
它返回null,因为您实际上从未设置变量。
CLASSA Ccs = new CLASSA(gsm); @Override public void init() { getFirstCompanion(); getVariables(); } private void getVariables() { classChoice = Ccs.getClassChoice(); System.out.println("Init, class is " + classChoice); //here, this returns as nothing, not null, nothing }您会看到,在声明new CLASSA(gsm)时,您正在创建一个全新的对象,您对前一个对象所做的任何更改都不会被反映出来,因为这是一个新的新对象 ,因此它的selectedClass属性被初始化为null 。 由于您在未事先设置的情况下获取该值,因此您将获得空值
我希望自己足够清楚,希望能帮助你!
编辑
如果要跨多个实例共享同一个变量,可以将它们设置为static :
private static String chosenClass = ""; public static void setChosenClass(String chosenClass) { this.chosenClass= chosenClass; } public static String getChosenClass() { return chosenClass; }It returns null because you actually never set the variable.
CLASSA Ccs = new CLASSA(gsm); @Override public void init() { getFirstCompanion(); getVariables(); } private void getVariables() { classChoice = Ccs.getClassChoice(); System.out.println("Init, class is " + classChoice); //here, this returns as nothing, not null, nothing }You see, you are creating a totally new object when declaring new CLASSA(gsm), any changes you made to a previous object is not reflected, because this a fresh new object, therefore its chosenClass attribute, is initialized to null. Since you are getting the value without previously setting it, you are getting a null value
I hope I made myself clear enough, and I hope I helped you!
Edit
If you want to share the same variable across multiple instances, you can make them static:
private static String chosenClass = ""; public static void setChosenClass(String chosenClass) { this.chosenClass= chosenClass; } public static String getChosenClass() { return chosenClass; }更多推荐
发布评论