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

(singke) #1
ptg7068951

148 HOUR 11:Describing What Your Object Is Like


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 Virusclass, you might have a method that has its own
variable called author:
publicvoid checkAuthor() {
String author = null;
}

A variable called authorexists within the scope of the checkAuthor()
method, but it isn’t the same variable as an object variable called author. If
you want to refer to the current object’s authorvariable, you have to use
the thisstatement, 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 thisanywhere in a class that you would refer to an
object by name. If you want 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 thisstatement is not needed to make it clear that
you’re referring to an object’s variables and methods. However, there’s no
detriment to using thisany time you want to be sure you’re referring to
the right thing.
The thiskeyword comes in handy in a constructor when setting the value
of an object’s instance variables. Consider a Virusobject that has author
and maxFileSizevariables. This constructor sets them:
public Virus(String author, int maxFileSize) {
this.author = author;
this.maxFileSize = maxFileSize;
}

Using Class Methods and Variables
At the insistence of our attorney, the next project is not the creation of a
working virus. Instead, you create a simple Virusobject that can count the
number of Virusobjects that a program has created and report the total.
Choose File, New File in NetBeans and create a new Empty Java File called
Virus. Enter Listing 11.1 in the source editor.
Free download pdf