简体   繁体   English

如何从一个类到另一个类调用变量?

[英]How can I call a variable from a class to another class?

For example, i have class a,b,c,d,e,f. 例如,我有a,b,c,d,e,f类。 and for class f, they have many variable, so how can I call class f variable when i am in class a,b,c,d,e? 对于f类,它们有很多变量,那么当我在a,b,c,d,e类中时,如何调用f类变量? Use import? 使用导入? or use static variable? 还是使用静态变量? Can static variable change while programming? 编程时静态变量可以改变吗? Thank you. 谢谢。

Multiple ways: 多种方式:

  • Define variable as static, final and public if that value doesn't change and is a constant. 如果该值不变且为常数,则将变量定义为static,final和public。

     public static final int DUMMY = 9999; 

And then you could access it like: 然后您可以像这样访问它:

    System.out.println(F.DUMMY);
  • Define that variable as instance variable and provide getter and setter in f class. 将该变量定义为实例变量,并在f类中提供getter和setter。 Inject instance of f within a,b.. classes and use getter/setter 在a,b ..类中注入f的实例,并使用getter / setter

      public class F { private int dummy; //getter/setter } public class a { .. int value = f.getDummy(); } 

Can static variable change while programming? 编程时静态变量可以改变吗?

Yes static fields can be changed later after declaring it.But only one value is maintained through out one instance of JVM. 是的,静态字段在声明后可以更改。但是在一个JVM实例中仅维护一个值。

No matter how many instance of class is created the static fileds within the class will be same for all the instance of class. 无论创建了多少个类实例,该类中的静态文件对于所有类实例都是相同的。

Here is good explaination in jls. 这是jls中的好解释。

Static Fields Explaination 静态场说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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