Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are fields in Java private by default?

Tags:

java

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?
like image 897
Madmenyo Avatar asked Sep 28 '14 16:09

Madmenyo


3 Answers

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

like image 148
August Avatar answered Sep 18 '22 15:09

August


By default is not private, is "package only" (no key word for that).

All classes in same package see the field.

like image 41
ben.12 Avatar answered Sep 20 '22 15:09

ben.12


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;}
like image 36
gkrls Avatar answered Sep 17 '22 15:09

gkrls