Access Modifiers


We discussed access modifiers in Chapter 7. The purpose of an access modifier is the same for variables as it is for classes. An access modifier applied to a variable defines how the variable can be accessed outside of the class in which it is defined. There are four types of access applicable to a variable: public , protected , private , and default.

  • public ” accessible anywhere inside or outside of the class in which the variable is defined.

  • protected ” accessible to any class defined in the same package as the variable. Outside of the package it is available only to subclasses of its class. This can be useful if you want to give subclasses direct access to a variable defined in a superclass, but don't want the variable accessible to the world at large.

  • private ” accessible only to the class in which the variable is defined. There is one school of thought that contends that all data members should be given private access. This ensures that the only access to them will be through methods .

  • default ” if no access modifier is provided, a variable is available to any class defined in the same package as the variable (i.e., public ). Outside of the package it is not available (i.e., private ).

The access types and ramifications are summarized in Table 8.2. Note that variables are always available inside the class in which they are defined regardless of their access modifiers. It is only for access outside of the variable's class that access modifiers come into play.

It is generally considered bad form to declare instance variables as public . By doing so you lose some control over your class. Someone who uses the class for another application might do things with your data members that you never intended, such as change the value of a variable that was intended to be read-only. Or someone could inadvertently set a length or weight to be negative.

Table 8.2. Variable Accessibility

V ARIABLE ACCESS TYPE

S AME CLASS

S AME PACKAGE

S UBCLASS, DIFFERENT PACKAGE

N ON-SUBCLASS, DIFFERENT PACKAGE

public

Yes

Yes

Yes

Yes

protected

Yes

Yes

Yes

No

private

Yes

No

No

No

default

Yes

Yes

No

No

The proper way to access variables outside the class in which they are defined is by using methods. The methods can make sure that the variables are not set to inappropriate values. This goes back to satisfying the object-oriented concept of encapsulation.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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