Access Specifiers in Java

Started by
2 comments, last by Aldacron 19 years, 4 months ago
Hi! I apologize for my question, for I am sure the answer is simple. My questions concerns the keywords public, protected, and private. I understand very fully what the three keywords do to members, but I am lost concerning what they do to class definitions. For example, private class MyClass { // code here } What do each of the three access specifiers do when they are used in such a context? Thanks for your help. ^_^
Advertisement
To understand it, you need to understand packages. You are probably already familiar with packages in java (java.util, java.awt, etc...). Packages are like namespaces in other languages.

Using public/protected/private on a member determines the member's accesibility outside the class. In the same way, using public/protected/private on a class determines the class's accessibility outside the package.

The keywords public/protected/private can be used for inner classes in the same way.

There is also a 'default' protection level if you don't use one of those three keywords.

I wish I could remember what protected/private/'default' do, but I haven't done much work with Java packages.
This is easy to test:

foo/Foo.java
package foo;class Foo { // change the access modifier as desired, see if it compiles   public int pub;  protected int prot;  private int priv;  int pack;}


Bar.java
// Try moving this into or out of the package, and making it// extend Foo or not// If inside the package:// package foo;// otherwise:// import foo.Foo;class Bar { // "extends Foo" possibly  public static void main(String[] args) {    Foo f = new Foo();    // in the subclassing case, also try making f be a Bar    int i = f.pub;    i = f.prot;    i = f.priv;    i = f.pack;    // see which if any lines are complained about  }}
The only thing to be concerned about with classes is whether to make one public, or not.

The following means any class from any package can import MyClass:

public class MyClass

Omitting the public keyword means only classes from the same package as MyClass can import it:

class MyClass

The protected and private modifiers have no meaning at the class level. They can be used for inner classes, however, and in that case have the same meaning as they do for when used with methods.

Also, when omitting any access modifier from a method or inner class, that method or inner class has package protection by default.

This topic is closed to new replies.

Advertisement