Home : Course Map : Chapter 5 : Java :
Access (Visibility) Rules
JavaTech
Course Map
Chapter 5
File/Package/Import
  Demo 1
  Demo 2
Access/Visibility
final & Constants
Static Import
Jar Files
  Demo 3
Applet Directories
3rd Party Packages
CLASSPATH
javadoc
CodingConventions
Exercises

    Supplements
Scope
Debug Techniques
Java Runtime
Class Class
JVM Instructions 2
JVM Processing
pack200

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

Access or visibility rules determine whether a method or a data variable can be accessed by another method in another class or subclass.

We have used the public modifier frequently in class definitions. It makes classes, methods, or data available to any other method in any other class or subclass.

Java provides for 4 access modifiers :

  1. public - access by any other class anywhere.

  2. protected - accessible by the package classes and any subclasses that are in other packages .

  3. Default - (also known as "package private") accessible to classes in the same package but not by classes in other packages, even if these are subclasses.

  4. private - accessible only within the class. Even methods in subclasses in the same package do not have access.

Note that a java file can have only one public class.

These access rules allow one to control the degree of encapsulation of your classes. For example, you may distribute your class files to other users who can make subclasses of them. By making some of your data and methods private, you can prevent the subclass code from interfering with the internal workings of your classes.

Also, if you distribute new versions of your classes at a later point, you can change or eliminate these private attributes and methods without worrying that these changes will affect the subclasses.

As we mentioned earlier, if you do not put your class into a package, it is placed into the "default unnamed package". For simple demonstration programs this usually suffices. However, with more serious programs you should use packages since otherwise any other class in the unnamed package has access to your class's fields and methods that are not set to private.

 

Most recent update: Oct. 22, 2004

            Tech
DecimalFormat
  Demo 1
  Demo 2

System.out.printf
  Demo 3
CJ Format Class
  Demo 4   Demo 5
Other Format Tools

Immutable Complex
Exercises

           Physics
Interpolation
Integration
  Demo 1
Simpson Rule
  Demo 2
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.