7.1 Access to Classes, Interfaces, Fields, and Methods

 <  Day Day Up  >  

7.1 Access to Classes, Interfaces, Fields, and Methods

The object-oriented Java language provides mechanisms for limiting access to classes, interfaces, fields, and methods. A class or an interface is said to be public if it is declared using the public keyword, in which case it may be accessed, using its qualified name , by any Java code that can access the package in which the class or interface is declared. A nonpublic class or interface may be accessed only from the package in which it is declared and is said to have default access . The effect of the public keyword on classes and interfaces is shown in Figure 7.2.

Figure 7.2. Access Restrictions to Classes and Interfaces

graphics/07fig02.gif

A class member ”a field, a method, or a constructor ”may be declared using at most one of the public , private , or protected keywords.

  • A private member may be accessed only from within the class that contains its declaration. In particular, this means that this member may be accessed by any instance of that class type.

  • A member that is not declared public, protected, or private is said to have default access and may be accessed from, and only from, anywhere in the package in which it is declared.

  • A protected member of an object may be accessed only by the code responsible for the implementation of that object. To be precise, a protected member may be accessed from anywhere in the package in which it is declared, as well as from within any subclass of the class type that contains its declaration. This means that a protected member is less protected than a member with default access.

  • A public member may be accessed by any Java code.

The effect of the access modifiers on class members is shown in Figure 7.3. Note that every field or method of an interface must be public. Every member of a public interface is implicitly public, whether or not the keyword public appears in its declaration. If an interface is not public, every one of its fields and methods must be explicitly declared public.

Figure 7.3. Effect of Access Modifiers on Members

graphics/07fig03.jpg

 <  Day Day Up  >  


Enterprise Java Security. Building Secure J2EE Applications
Enterprise Javaв„ў Security: Building Secure J2EEв„ў Applications
ISBN: 0321118898
EAN: 2147483647
Year: 2004
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net