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

(singke) #1
ptg7068951

146 HOUR 11:Describing What Your Object Is Like


Rules that enforce scope make programs easier to debug because scope
limits the area in which you can use a variable. This reduces one of the
most common errors that can crop up in programming—using the same
variable two different ways in different parts of a program.
The concept of scope also applies to methods because they are defined by
an opening bracket and closing bracket. Avariable created inside a method
cannot be used in other methods. You only can use a variable in more than
one method if it was created as an object variable or class variable.

Putting One Class Inside Another
Althougha Java program is called a class, there are many occasions when
a program requires more than one class to get its work done. These pro-
grams consist of a main class and any helper classes that are needed.
When you divide a program into multiple classes, there are two ways to
define the helper classes. One way is to define each class separately, as in
the following example:
public classWrecker {
String author = “Ignoto”;

public voidinfectFile() {
VirusCode vic = new VirusCode(1024);
}
}

classVirusCode {
int vSize;

VirusCode(int size) {
vSize = size;
}
}

In this example, the VirusCodeclass is a helper class for the Wreckerclass.
Helper classes often are defined in the same source code file as the class
they’re assisting. When the source file is compiled, multiple class files are
produced. The preceding example produces the files Wrecker.classand
VirusCode.classwhen compiled.
When creating a main class and a helper class, you also can put the helper
inside the main class. When this is done, the helper class is called an inner
class.

CAUTION
If more than one class is
defined in the same source file,
only one of the classes can be
public. The other classes
should not have publicin their
class statements. The name of
the source code file must
match the publicclass that it
defines.

Free download pdf