Professional Documents
Culture Documents
Attributes are the information stored within an object. They can be variables such as integers, characters,
Boolean values, or other objects such as String and Calendar objects. Behavior is the groups of
statements used to handle specific jobs within the object. Each of these groups is called a method.
Up to this point, you have been working with the methods and variables of objects without knowing it. Any
time your statement had a period in it that wasn't a decimal point or part of a string, chances are an object
was involved. You'll see this during this hour as the following topics are covered:
Creating Variables
For the purposes of this hour's examples, you'll be looking at a class of objects called Virus whose sole
purpose in life is to reproduce in as many places as possible—much like some of the people I knew in
college. A Virus has several different things it needs in order to do its work, and these will be
implemented as the behavior of the class. The information that's needed for the methods will be stored as
attributes.
Note
This hour will not teach actual virus writing, though it might provide some insight into how virus programs
work as they wreak havoc on the file systems of the computer-loving world. This publisher had scheduled
Sams Teach Yourself Virus Programming in a Three-Day Weekend for next spring, but the book has been
postponed because the author's hard drive was unexpectedly erased by an email from someone who said
"I love you" but had a funny way of showing it.
The attributes of an object represent any variables needed in order for the object to function. These
variables could be simple data types such as integers, characters, and floating-point numbers, or they
could be arrays or objects of classes such as String or Calendar. An object's variables can be used
throughout its program, in any of the methods the object includes. You create variables immediately after
the class statement that creates the class and before any methods.
One of the things that a Virus object 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 is a sign that the file was infected. The Virus object will use 86 as the
seconds field of a file's modification time because "86 it" is slang that means to throw something away—
exactly the kind of unpleasant antisocial connotation we're going for. The value will be stored in an integer
variable called newSeconds.
The following statements begin a class called Virus with an attribute called newSeconds and two other
attributes:
All three variables are attributes for the class: newSeconds, maxFileSize, and author.
Putting a statement such as public in a variable declaration is called access control, because it
determines how other objects made from other classes can use that variable— or if they can use it at all.
The newSeconds variable has a starting value of 86, and the statement that creates it has public as
the first part of the statement. Making a variable public makes it possible to modify the variable from
another program that is using the Virus object. If the other program attaches special significance to the
number 92, for instance, it can change newSeconds to that value. The following statements create a
Virus object called influenza and set its newSeconds variable:
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 author variable can be
changed to any name or pseudonym that identifies the author of the virus, and the only restriction is
aesthetic. The name might eventually be used on court documents if you're 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 Virus class, if newSeconds is set to a value of 60 or less, it won't be 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,
and they'll look infected to Virus. If the Virus class of objects needs to guard against this problem, you
• Switch the variable from public to protected or 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.
A protected variable can only be used in the same class as the variable, any subclasses of that class, or
by classes in the same package. A package is a group of related classes that serve a common purpose. An
example is the java.util package, which contains classes that offer useful utility functions, such as date
and time programming and file archiving. When you use the import statement in a Java program with an
asterisk, as in import java.util.*;, you are making the classes of a package available for use in
that program.
A private variable is restricted even further than a protected variable—it only can be used in the
same class. Unless you know that a variable can be changed to anything without affecting how its class
functions, you probably should make the variable private or protected.
If you want other programs to use the newSeconds variable in some way, you'll have to create behavior
that makes it possible. This task will be covered later in the hour.
There also is another type of access control: the lack of any public, private, or pro tected
There are times when an attribute has more to do with an entire class of objects than a specific object itself.
For example, if you wanted to keep track of how many Virus objects were being used in a program, it
would not make sense to store this value repeatedly in each Virus object. Instead, you can use a class
variable to store this kind of information. You can use this kind of variable with any object of a class, but
only one copy of the variable exists for the whole class. The variables you have been creating for object
thus far can be called object variables, because they are tied to a specific object. Class variables refer to a
class of the objects as a whole.
Both types of variables are created and used in the same way, except that static is used in the
statement that creates class variables. The following statement creates a class variable for the Virus
example:
Changing the value of a class variable is no different than changing an object's variables. If you have a
Virus object called tuberculosis, you could change the class variable virusCount with the
following statement:
tuberculosis.virusCount++;
Because class variables apply to an entire class instead of a specific object, you can use the name of the
class instead:
Virus.virusCount++;
Both statements accomplish the same thing, but there's an advantage to using the name of the class when
working with class variables. It shows immediately that virusCount is a class variable instead of an
object's variable, because you can't refer to object variables using the name of a class. If you always use
object names when working with class variables, you won't be able to tell whether they are class or object
variables without looking carefully at the source code of the class.
You have been using methods throughout your programs up to this point without knowing it, including one
in particular: println(). This method displays text onscreen. Like variables, methods are used in
connection with an object or a class. The name of the object or class is followed by a period and the name
of the method, as in screen2D.drawString() or Integer.parseInt().
Note
The System.out.println() method might seem confusing because it has two periods instead of one.
This is because two classes are involved in the statement—the System class and the PrintStream
class. The System class has a variable called out that is a PrintStream object. println() is a
method of the PrintStream class. The System.out.println() statement means, in effect, "Use the
println() method of the out variable of the System class." You can chain together references to
variables and methods in this way.
Declaring a Method
You create methods with a statement that looks similar to the statement that begins a class. Both can take
arguments between parentheses after their names, and both use { and } marks at the beginning and end.
The difference is that methods can send back a value after they are handled. The value can be one of the
simple types such as integers or Boolean values, or it can be a class of objects. If a method should not
return any value, use the void statement.
The following is an example of a method the Virus class can use to infect files:
The infectFile() method is used to add a virus to a file. This method takes a single argument, a string
variable called filename, and this variable represents the file that should be attacked. The actual code to
infect a file is omitted here due to the author's desire to stay on the good side of the U.S. Secret Service.
The only thing you need to know is that if the infection is a success, the success variable is set to a value
of true.
By looking at the statement that begins the method, you can see boolean preceding the name of the
method, infectFile. This statement signifies that a boolean value will be sent back after the method
is handled. The return statement is what actually sends a value back. In this example, the value of
success is returned.
When a method returns a value, you can use the method as part of an assignment statement. For example,
if you created a Virus object called malaria, you could use statements such as these:
if (malaria.infectFile(currentFile))
System.out.println(currentFile + " has been infected!");
else
System.out.println("Curses! Foiled again!");
Any method that returns a value can be used at any place a value or variable could be used in a program.
Earlier in the hour, you switched the newSeconds variable to private to prevent it from being set by
other programs. However, because you're a virus writer who cares about people, you still want to make it
possible for newSeconds to be used if it is used correctly. The way to do this is to create public
methods in the Virus class that read the value of newSeconds or write a new value to newSeconds.
These new methods should be public, unlike the newSeconds variable itself, so they can be called by
other programs. The new methods will be able to work with newSeconds because they are in the same
The getSeconds() method is used to send back the current value of newSeconds. The
getSeconds() method is necessary because other programs can't even look at a private variable
such as newSeconds. The getSeconds() method does not have any arguments, but it still must have
parentheses after the method name. Otherwise, when you were using getSeconds in a program, the
The setSeconds() method takes one argument, an integer called newValue. This integer contains the
value that a program wants to change newSeconds to. If newValue is greater than 60, the change will
be made. The setSeconds() method has void preceding the method name, so it does not return any
kind of value.
In this example, the Virus class controls how the newSeconds variable can be used by other classes.
This process is called encapsulation, and it's a fundamental concept of object-oriented programming. The
better your objects are able to protect themselves against misuse, the more useful they will be when you
use them in other programs.
As you have seen with the setSeconds() method, you can send arguments to a method to affect what it
does. Different methods in a class can have different names, but methods can also have the same name if
they have different arguments.
Two methods can have the same name if they have a different number of arguments, or the specific
arguments are of different variable types. For example, it might be useful for the Virus class of objects to
have two tauntUser() methods. One could have no arguments at all and would deliver a generic taunt.
The other could specify the taunt as a string argument. The following statements could implement these
methods:
void tauntUser() {
System.out.println("The problem is not with your set, but "
+ "with yourselves.");
}
Constructor Methods
When you want to create an object in a program, the new statement is used, as in the following example:
This statement creates a new Virus object called typhoid. When you use the new statement, a special
method of that object's class is called. This method is called a constructor because it handles the work
required to create the object. The purpose of a constructor is to set up any variables and other things that
need to be established for the object to function properly.
Constructor methods are defined like other methods, except that they cannot return a value as other
methods do. The following are two constructor methods for the Virus class of objects:
public Virus() {
author = "Ignoto";
maxFileSize = 30000;
}
Like other methods, constructors can use the arguments they are sent as a way to define more than one
constructor in a class. In this example, the first constructor would be called when a new statement such as
The other constructor could be called only if a string and an integer were sent as arguments with the new
If you don't include any constructor methods in a class, it will inherit a single constructor method with no
arguments from its superclass. There also might be other constructor methods that it inherits, depending on
the superclass used.
In any class, there must be a constructor method that has the same number and type of arguments as the
new statement that's used to create objects of that class. In the example of the Virus class, which has
Virus() and a Virus(String name, int size) constructors, you only could create Virus
objects with two different types of new statements: one without arguments and one with a string and an
Class Methods
Like class variables, class methods are a way to provide functionality associated with an entire class
instead of a specific object. Use a class method when the method does nothing that affects an individual
object of the class. One example that you have used in a previous hour was the parseInt() method of
the Integer class. This method is used to convert a string to a variable of the type int, as in the
following:
To make a method into a class method, use static in front of the method name, as in the following:
Virus.showVirusCount();
When you create a variable or an object inside a method in one of your classes, it is usable only inside that
method. The reason for this is the concept of variable scope. Scope is the section in which a variable exists
in a program. If you go outside of the part of the program defined by the scope, you can no longer use the
variable.
The { and } statements in a program define the boundaries for a variable. Any variable created within
these marks cannot be used outside of them. For example, consider the following statements:
if (numFiles < 1) {
String warning = "No files remaining.";
}
System.out.println(warning);
This example does not work correctly because the warning variable was created inside the brackets of
the if block statement. Those brackets define the scope of the variable. The warning variable does not
exist outside of the brackets, so the System.out.println() method cannot use it as an argument.
When you use a set of brackets inside another set of brackets, you'll need to pay attention to the scope of
the variables with which you are working. Take a look at the following example:
if (infectedFiles < 5) {
int status = 1;
if (infectedFiles < 1) {
boolean firstVirus = true;
status = 0;
} else {
firstVirus = false;
}
}
In this example the status variable can be used anywhere, but the firstVirus variable will cause a
compiler error. Because firstVirus is created within the scope of the if (infectedFiles < 1)
statement, it doesn't exist inside the scope of the else statement that follows.
To fix the problem, firstVirus must be created outside both of these blocks so that its scope includes
both of them. One solution would be to create firstVirus at the same time that status is created.
Rules that enforce scope make programs easier to debug because scope limits the area in which a variable
can be used. This reduces one of the most common errors that can crop up in many programming
languages: the same variable being used two different ways in different parts of a program. By enforcing
restrictive rules for a variable's scope, the Java language makes it more difficult to misuse a variable.
The concept of scope applies to methods also, because they are defined by an opening bracket and
closing bracket. A variable created inside a method cannot be used in other methods. You can only use a
variable in more than one method if it was created as an object variable or class variable after the class
An example might be a Java applet that displays a scrolling headline as part of its graphical user interface.
The headline could be an independent object in the program, just like other interface elements such as
buttons and scroll bars. It makes sense to put the headline into its own class, rather than including its
variables and methods in the applet class.
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:
class VirusCode {
int vSize;
VirusCode(int size) {
vSize = size;
}
}
In this example, the VirusCode class is being used as a helper of the WreakHavoc class. Helper
classes will often be defined in the same .java source file as the class they're assisting. When the source
file is compiled, multiple class files will be produced. The preceding example would produce the files
WreakHavoc.class and VirusCode.class.
Note
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 public in their class statements. Also, the name of the source file should
match the name of the public class. In the preceding example, the name should be
WreakHavoc.java.
When creating a main class and a helper class, you can also put the helper inside the main class. When
this is done, the helper class is called an inner class.
An inner class is placed within the opening bracket and closing bracket of another class.
class VirusCode {
int vSize;
VirusCode(int size) {
vSize = size;
}
}
}
An inner class can be used in the same manner as any other kind of helper class. The main difference—
other than its location—is what happens after the compiler gets through with these classes. Inner classes
do not get the name indicated by their class statement. Instead, the compiler gives them a name that
This section illustrates one of the simplest examples of how an inner class can be defined and used. Inner
classes are an advanced feature of Java that you won't encounter often as you first learn the language.
The functionality they offer can be accomplished by using helper classes defined separately from a main
class, and that's the best course to take as you're starting out in programming.
When you are using an object's methods or variables, you put the name of the object in front of the method
or variable name, separated by a period. Consider these examples:
These statements create a new Virus object called chickenpox, set the name variable of
chickenpox, and then call the setSeconds() method of chickenpox.
There are times in a program when you need to refer to the current object—in other words, the object
represented by the program itself. For example, inside the Virus class, you might have a method that has
its own variable called author:
A variable called author exists within the scope of the checkAuthor() method, but it isn't the same
variable as an object variable called author. If you wanted to refer to the current object's author
variable, you have to use the this statement, as in the following:
System.out.println(this.author);
By using this, you make it clear to which variable or method you are referring. You can use this
anywhere in a class that you would refer to an object by name. If you wanted to send the current object as
an argument in a method, for example, you could use a statement such as the following:
verifyData(this);
In many cases, the this statement will not be needed to make it clear that you're referring to an object's
variables and methods. However, there's no detriment to using this any time you want to be sure you're
Load your word processor and create a new file called Virus.java. Enter Listing 11.1 into the word
Compile the file and return to your word processor. To test out this new Virus class, you need to create a
second class that can create Virus objects.
The VirusLook class is a simple application that creates Virus objects and then counts the number of
objects that have been created with the getVirusCount() class method of the Virus class.
Open up a new file with your word processor and enter Listing 11.2. Save the file as VirusLook.java
The VirusLook class is an application that takes one argument when you run it at the command line: the
number of Virus objects to create. The following is an example of a command that can be used to run the
application:
Arguments are read into an application using a string array that's sent to the main() method. In the
VirusLook class, this occurs in Line 2.
To work with an argument as an integer, it must be converted from a String object to an integer. This
requires the use of the parseInt() class method of the Integer class. In Line 3, an int variable
named numViruses is created from the first argument sent to the program on the command line.
If the numViruses variable is greater than 0, the following things take place in the VirusLook
application:
• Line 5: An array of Virus objects is created with the numViruses variable determining the number
• Lines 6–7: A for loop is used to call the constructor method for each Virus object in the array.
• Lines 8–9: After all of the Virus objects have been constructed, the getVirusCount() class
method of the Virus class is used to count the number of its objects that have been created. This
should match the argument that was set when the VirusLook application was run.
If the numViruses variable is not greater than 0, nothing happens in the VirusLook application.
After you compile the VirusLook.java file, test it with any command-line argument you'd like to try. The
number of Virus objects that can be created depends on the memory that's available on your system
when you run the VirusLook application. On the author's system, anything above 5.6 million viruses
causes the program to crash after displaying an OutOfMemoryError message.
If you don't specify more Virus objects than your system can handle, the output should be something like
the following:
Summary
You now have completed two of the three hours devoted to object-oriented concepts in this book. You've
learned how to create an object, give behavior and attributes to the object and its class of objects, and
convert objects and variables into other forms by using casting.
Thinking in terms of objects is one of the tougher challenges of the Java programming language. Once you
start to understand it, however, you realize that the entire language makes use of objects and classes.
During the next hour, you'll learn how to give your objects parents and children.