ptg7068951
138 HOUR 11:Describing What Your Object Is Like
One of the things that a Virusobject needs is a way to indicate that a file
already has been infected. Some computer viruses change the field that
stores the time a file was last modified; for example, a virus might move
the time from 13:41:20 to 13:41:61. Because no normal file would be saved
on the 61st second of a minute, the time signifies that the file was infected.
The Virusobject uses the impossible seconds value 86 in an integer vari-
able called newSeconds.
The following statements begin a class called Viruswith an attribute called
newSecondsand two other attributes:
public classVirus {
public intnewSeconds = 86;
public String author = “Sam Snett”;
int maxFileSize = 30000;
}
All three variables are attributes for the class: newSeconds, maxFileSize,
and author.
Putting a statement such as publicin a variable declaration statement is
called access controlbecause it determines how other objects made from
other classes can use that variable—or if they can use it at all.
Making a variable publicmakes it possible to modify the variable from
another program that is using the Virusobject.
If the other program attaches special significance to the number 92, for
instance, it can change newSecondsto that value. The following statements
create a Virusobject called influenzaand set its newSecondsvariable:
Virus influenza = new Virus();
influenza.newSeconds = 92;
In the Virusclass, the authorvariable also is public, so it can be changed
freely from other programs. The other variable, maxFileSize, can be used
only within the class itself.
When you make a variable in a class public, the class loses control over
how that variable is used by other programs. In many cases, this might not
be a problem. For example, the authorvariable can be changed to any
name or pseudonym that identifies the author of the virus. The name
might eventually be used on court documents if the author is prosecuted,
so you don’t want to pick a dumb one. The State of Ohio v. LoveHandles
doesn’t have the same ring to it as Ohio v. MafiaBoy.
Restricting access to a variable keeps errors from occurring if the variable
is set incorrectly by another program. With the Virusclass, if newSeconds