Default Scope in Java
As your Java applications become more complex, the need to consider scope becomes ever more important. The main reason is that you can inadvertently introduce a bug into your application by not observing scoping rules.
This can result from a field or other member being used incorrectly by the application (such as adding an incorrect data value or accessing a method at the wrong time or with incorrect data). In addition, incorrect scoping can leave the door open for outsiders to interact with your application in unforeseen ways (such as a virus).
The default scope occurs when you don’t specifically assign a scope to a class element. Because many Java developers have no idea what the default scope is for some elements (and using a default scope means that your code isn’t documented), it isn’t used very often.
Even so, you need to know what the default scope is for various elements because some Java developers do rely on it. However, before you can understand the default scope, you need to consider visibility — the measure of which application elements can see a member. Java provides the following levels of visibility (in general order of encapsulation):
Package: The container used to hold a number of classes. When working with a simple directory structure, as the examples in this book do, the package is a directory that holds a number of .class files.
Class: A class usually resides in a single .java file that you compile into a .class file. It contains a single class declaration.
Method: An element can reside in the class or as part of a method. The method acts as a container to hold the element.
Block: An element can reside within a code block, such as a for loop.
Scope partially depends on the location used to declare an element. For example, a variable that’s defined within a block (such as a for loop) is visible only within that block. When you try to use the variable outside of the block, Java displays an exception. Taking visibility into account, this table describes the various levels of scope within the Java environment.
|Accessible from the class||X||X||X||X|
|Accessible from the package||X||X||X|
|Accessible from any child class||X||X|
The table shows how the default scope fits into the scheme of things. For example, if you declare a method by using the default scope, any method can use it as long as it resides in the same package. In addition, if you create a class that inherits from the class containing the method, the subclass can use the method as long as it resides in the same package.
However, if the subclass exists outside the current package, it can’t use the method. In short, the default scope is a little more restrictive than the protected scope, but less restrictive than the private scope.