2

Slightly related to my other question: What is the difference between the following:

private class Joe
protected class Joe
public class Joe
class Joe

Once again, the difference between the last 2 is what I'm most interested in.

Community
  • 1
  • 1
Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • I've only just read your other question. Given the answers to that one, this question is redundant. Yes, they're slightly different questions - but the references given cover class accessibility as well as variables. – Jon Skeet Nov 06 '08 at 06:33

3 Answers3

17

A public class is accessible to a class in any package.

A class with default access (class Joe) is only visible to other classes in the same package.

The private and protected modifiers can only be applied to inner classes.

A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.

A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.

erickson
  • 265,237
  • 58
  • 395
  • 493
1
  • private: visible for outer classes only
  • protected: visible for outer classes only
  • public: visible for all other classes
  • class: package-private, so visible for classes within the same package

See JLS for more info.

Daniel Hiller
  • 3,415
  • 3
  • 23
  • 33
1

A class with default access has no modifier preceding it in the declaration.

The default access is a package-level access, because a class with default access can be seen only by classes within the same package.

If a class has default access, a class in another package won’t be able to create a instance of that class, or even declare a variable or return type. The compiler will complain. For example:

package humanity;
class Person {}

package family;
import humanity.Person;
class Child extends Person {}

Try to compile this 2 sources. As you can see, they are in different packages, and the compilation will fail.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250