48

I'd like to be able to have two "protected" classes in my package. That is, I do not want files outside of my package to see them as visible - they will be for internal use within the package only.

How can I do this?

Cam
  • 14,930
  • 16
  • 77
  • 128

1 Answers1

87

Just leave out all keywords. The default visibility is package-private, viewable within the package only.

e.g.:

// class Foo is public
public class Foo
{
    final private Bar bar = ...;
}

// class Bar is package-private
// (visible to all classes in the package, not visible outside the package)
class Bar
{
    ...;
}
Jason S
  • 184,598
  • 164
  • 608
  • 970
  • 1
    Exactly. And the keyword protected means that it is only accessible by derived types – Oskar Kjellin Mar 28 '10 at 22:01
  • 1
    @Oskar: well, technically it looks like protected is visible by derived types *outside* the package, and *all* types inside the package. – Jason S Mar 28 '10 at 22:03
  • 1
    surely classes outside Bar's package can't even see the Bar class, so they can't extend it. (What happens if a public class inside the package extends it though...?) – Bennett McElwee Mar 28 '10 at 22:18
  • **Jakson S**, you are absolutely right, all the levels of access include each other in order. **private** allows access within the class, **package-private** (default) allows access within the package *and* within the class, **protected** allows access for child classes of other packages *and* within the package, finally **public** allows anything to have access and thus includes all other levels. **Bennett McElwee**, protected members remain protected unless they are methods and they get overriden. But even then it would be overriden method that is allowed to be accessed. – Malcolm Mar 28 '10 at 22:21
  • If you don't want that any other class inherit, you can add `public final`, this allows you use the class but any class can inherit – kelgwiin Jun 17 '15 at 14:04