42

If instead of:

private JButton theButton;

I define a field like this:

JButton theButton;

What is the difference?

4 Answers 4

53

Package. They're visible to other classes in the same package.

FWIW, I usually use my own no-op @Package annotation on these, just to make it clear that I know what I'm doing - that I didn't just forget something. Even though it's the default, package access is probably used less in high-quality code than any of the other three possibilities - with one big exception:

In some styles of unit testing, it's desirable to be able to get access to methods or fields that are normally private. One way to provide access is to set them to package access, and put the unit test class in the same package (but usually in a different "test" directory tree). Some developers think that this is bad practice - that in general, it's bad to use private (or package-for-testing) methods in tests.

0
46

In Java there are public, protected, package (default), and private visibilities; ordered from most visible to the least.

If you do not specify it, by default the visibility is package.

package mytest.myvisibility;

public class MyClass
{
    public int myPublicInt; // visible to all
    protected myProtectedInt; // visible to subclasses of MyClass and to other members of the mytest.myvisibility package
    int myPackageInt; // visible only to other members of the mytest.myvisibility package
    private int myPrivateInt; // visible only to MyClass objects
}
2
  • This is not exactly true (see Oracle doc provided by @LukeH above). Protected items are also visible in current package. Commented Dec 7, 2015 at 14:27
  • 3
    updated -- elaborated on the "package" visibility, and made the order of visibilities consistent in the description and in the code sample. Commented Jan 7, 2016 at 4:42
6

Here's a useful overview showing access permitted by each modifier:

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 first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member (i.e. classes that extend this class). The fourth column indicates whether all classes have access to the member.

Source (Oracle)

-1

same as static function on c. only visible on the same file.

1
  • This is wrong. They are "package-private" as already elaborated in other answers which means they are visible not only in the same file but in other files of the same package as well. Commented Mar 25, 2018 at 11:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.