Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Creating Class Variables 139

is set to a value of 60 or less, it isn’t reliable as a way to tell that a file is
infected. Some files might be saved with that number of seconds regardless
of the virus. If the Virusclass of objects needs to guard against this prob-
lem, you need to do these two things:


. Switch the variable from publicto protectedor private, two other
statements that provide more restrictive access.
. Add behavior to change the value of the variable and report the
value of the variable to other programs.


You can use a protectedvariableonly in the same class as the variable,
any subclasses of that class, or classes in the same package. Apackageis a
group of related classes that serve a common purpose. An example is the
java.utilpackage, which contains classes that offer useful utilities such
as date and time programming and file archiving. When you use the
importstatement in a Java program with an asterisk, as in import
java.util.*, you are making it easier to refer to the classes of that pack-
age in a program.


Aprivatevariableis restricted even further than a protectedvariable—
you can use it only in the same class. Unless you know that a variable can
be changed to anything without affecting how its class functions, you
should make the variable privateor protected.


The following statement makes newSecondsa privatevariable:


private intnewSeconds = 86;


If you want other programs to use the newSecondsvariable in some way,
you have to create behavior that makes it possible. This task is covered
later in the hour.


There also is another type of access control: the lack of any public,
private, or protectedstatement when the variable is created.


In most of the programs you have created prior to this hour, you didn’t
specify any access control. When no access control is set, the variable is
available only to classes in the same package. This is called default or
package access.


Creating Class Variables


When youcreate an object, it has its own version of all variables that are
part of the object’s class. Each object created from the Virusclass of objects

Free download pdf