views:

152

answers:

6

So I just started reading a Java book and wondered; which access specifier is the default one if none is specified?

+10  A: 

The default visibility is known as “package” (though you can't use this keyword), which means the field will be accessible from inside the same package to which the class belongs.

See Java's Access Specifiers

Samuel_xL
Thanks! Great link.
bennedich
+3  A: 

If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.

Michael Borgwardt
A: 

See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.

Brian Agnew
+2  A: 

The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.

Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package

Johannes Wachter
+6  A: 

The default specifier depends upon context.

For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)

class MyClass   // package private
{
   int field;    // package private field

   void calc() {  // package private method

   }
}

For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.

interface MyInterface  // package private
{
   int field1;         // static final public

   void method1();     // public abstract
}

If we then have the declaration

public interface MyInterface2 extends MyInterface
{

}

Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.

mdma
"Package private" (sometimes written in source as `/* pp */`) is only a convenient name for *default access*. It's not the JLS name.
Tom Hawtin - tackline
@Tom - that's correct, the JLS uses "default access". I could have written "the default is default access". But that didn't seem too helpful!
mdma
A: 

Another interesting link:

http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers

Torres