views:

325

answers:

1

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?

+9  A: 

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
Cool - thanks. I'll come back in 11 minutes and accept this once SO says I can.
Cam
Exactly. And the keyword protected means that it is only accessible by derived types
Oskar Kjellin
@Oskar: well, technically it looks like protected is visible by derived types *outside* the package, and *all* types inside the package.
Jason S
@Jason S, 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
**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