next up previous
Next: Conversions Up: Week 4 Previous: What's a package, anyway?

What's the deal with public and private?

Well, you might ask what's the deal with public, private, and restricted. What we know so far is this: when we declare classes, member variables, and methods, we can put one of the Java keywords public or private in front of the declaration. We could also put neither. In this case the class, member variable, or method would be restricted. Notice that restricted is not a keyword of the Java language, so don't go putting it in front of any declaration.

But what does all this mean? Well, these words refer to the accessibility of the class or member, which means 'where can we refer to these classes or members?'. The keyword public makes a class, member, or constructor accessible to other packages, no keyword makes a class, member, or constructor accessible only to other classes in the same package (restricted), and the keyword private wouldn't be used with a class, but would make a member accessible within its class. (recall that a member is a member variable or method of a class)

Ahh, you say, but what if a class is restricted (and therefore only visible/accessible within its package) but a member of the class is public? Would the member than be accessible outside the package, while the class itself isn't? This doesn't make much sense. It turns out that members of a class can't be more accessible than the class itself.

So roughly speaking, we have:

  1. public: accessible in other packages
  2. restricted (no keyword): accessible only in its own package
  3. private: accessible only in its own class

which is illustrated in the diagram below:

Figure 18: Accessibility of members and classes
\begin{figure}
\begin{center}
\epsfxsize =5in {\epsfbox {package.ps}} \\
\end{center}\end{figure}


next up previous
Next: Conversions Up: Week 4 Previous: What's a package, anyway?
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09