Madmenyo
Madmenyo

Reputation: 8584

Are fields in Java private by default?

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?

Upvotes: 6

Views: 12351

Answers (5)

August
August

Reputation: 12558

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

Upvotes: 26

Ankit
Ankit

Reputation: 61

If you don't specify any modifier to any property/method then, it has default modifier. Which means it can be only accessed within same class or package. Whereas a private modifier restrict the property to be accessed within the defined class.

Upvotes: 1

gispyros
gispyros

Reputation: 56

The above link is valid and you should read it to see which access modifier can be applied to a class, struct, variable and etc.... But, in C# when no access modifier is available as in your second reference then the modifier is private by default, not internal. Internal is for classes and structs.

For Java is package visible

e.g.

class A{}

is the same with

internal class A{}

Upvotes: 0

gkrls
gkrls

Reputation: 2664

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;}

Upvotes: 2

ben.12
ben.12

Reputation: 51

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

All classes in same package see the field.

Upvotes: 5

Related Questions