所有 Java 类都可以看到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9654750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
variable seen by all classes Java
提问by Samiah
I'm a beginner in java, so I don't know if there is any way to make a variable seen by all classes in same package?
我是java初学者,不知道有没有什么办法可以让同一个包中的所有类都看到一个变量?
采纳答案by MByD
The default modifier (just don't write public
/private
/protected
) gives access from inside the package only. (Take a look here)
默认修饰符(只是不写public
/ private
/ protected
)给出了这只包内访问。(看这里)
But as a rule, it is a good practice to avoid accessing variables directly.
但作为一项规则,避免直接访问变量是一个好习惯。
Edit:
编辑:
Responding the comments, if you want to access this variable without creating an object, then it should be static:
回复评论,如果你想在不创建对象的情况下访问这个变量,那么它应该是静态的:
package com.some.package;
public class MyClass {
static int someInt = 1;
}
Then to access it, you need to qualify it by the class:
然后要访问它,您需要按类对其进行限定:
package com.some.package;
public class AnotherClass {
public void someMethod() {
int i = MyClass.someInt;
//^^^^^^^
}
}
回答by Jakub Zaverka
static <type> <variable name>;
static <类型> <变量名>;
If you do not supply access modifier, it defaults to package-private. It means that the variable is visible only to members of the same package.
如果您不提供访问修饰符,则默认为 package-private。这意味着该变量仅对同一包的成员可见。