Why do i see so many examples out there that type private in front of a field while afaik fields are private by default.
private int number;
int number;
//Both of these are the same afaik. Yet, in a ton of examples private gets fully written, why?
No, they're not the same. The lack of an access modifier defaults to package-private.
See this: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The exception to this rule is that interface
method and field signatures are public
when an access modifier is omitted: http://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
By default is not private, is "package only" (no key word for that).
All classes in same package see the field.
This is not the same thing. Not specifying an access modifier in Java, in this case private
, means that the default access modifier is used. i.e Anything on the same package with your class has access to those members.
The private
access modifier means that only that specific class will have acess to it's members.
The reason this happens is for a class to protect it's data and avoid accidental data corruption.
Please refer to this for more info.
Now if you want to access those members you have to create getter methods for example:
public class foo{
private int x = 5;
public int getX(){ return x;}
}
Similarly if you want to change a members value you create setter methods:
public int setX(int x){ this.x = x;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With