I know that in JavaScript, you don't need the public
keyword in the following code :
class myClass
{
public int myVariable;
// it is the same as :
int myVariable
}
do you need it in Java ? What is its purpose ?
I know that in JavaScript, you don't need the public
keyword in the following code :
class myClass
{
public int myVariable;
// it is the same as :
int myVariable
}
do you need it in Java ? What is its purpose ?
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.
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.
More details are here - http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
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.