I know that in JavaScript, you don't need the public
keyword in the following code :
我知道在JavaScript中,您不需要以下代码中的public关键字:
class myClass
{
public int myVariable;
// it is the same as :
int myVariable
}
do you need it in Java ? What is its purpose ?
你需要用Java吗?它的目的是什么?
3 个解决方案
#1
3
Yes if you want something to be accessible everywhere.
是的,如果你想要随处可访问的东西。
Otherwise it is package-visibility, meaning only stuff in the same package (at some level) can access it.
否则它是包可见性,这意味着只有同一个包(在某个级别)的东西才能访问它。
#2
2
You don't 'need' the 'public' keyword - if you don't specify the access level of a Class variable it will be set to package-private.
您不需要'public'关键字 - 如果您没有指定Class变量的访问级别,它将被设置为package-private。
More details are here - http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
更多细节在这里 - http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
#3
0
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
public fields are a bad idea, however (A VERY bad idea in a multi-threaded application). It allows other classes to change the state of your class without any control, and could break invariants. The proper way is to control state-changing through public setter methods.
然而,公共领域是一个坏主意(在多线程应用程序中一个非常糟糕的主意)。它允许其他类在没有任何控制的情况下更改类的状态,并且可以打破不变量。正确的方法是通过公共setter方法控制状态变化。
#1
3
Yes if you want something to be accessible everywhere.
是的,如果你想要随处可访问的东西。
Otherwise it is package-visibility, meaning only stuff in the same package (at some level) can access it.
否则它是包可见性,这意味着只有同一个包(在某个级别)的东西才能访问它。
#2
2
You don't 'need' the 'public' keyword - if you don't specify the access level of a Class variable it will be set to package-private.
您不需要'public'关键字 - 如果您没有指定Class变量的访问级别,它将被设置为package-private。
More details are here - http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
更多细节在这里 - http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
#3
0
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
public fields are a bad idea, however (A VERY bad idea in a multi-threaded application). It allows other classes to change the state of your class without any control, and could break invariants. The proper way is to control state-changing through public setter methods.
然而,公共领域是一个坏主意(在多线程应用程序中一个非常糟糕的主意)。它允许其他类在没有任何控制的情况下更改类的状态,并且可以打破不变量。正确的方法是通过公共setter方法控制状态变化。