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

(singke) #1
ptg7068951

Using the thisKeyword 147

You place an inner class within the opening bracket and closing bracket of
another class.


public classWrecker {
String author = “Ignoto”;


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

classVirusCode {
int vSize;

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


You can use an inner class 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 classstatement. Instead, the compiler gives them
a name that includes the name of the main class.


In the preceding example, the compiler produces Wrecker.classand
Wrecker$VirusCode.class.


Using the this Keyword


Because you can refer to variables and methodsin other classes along with
variables and methods in your own classes, the variable you’re referring to
can become confusing in some circumstances. One way to make things
more clear is with the thisstatement—a way to refer within a program to
the program’s own object.


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:


Virus chickenpox = new Virus();
chickenpox.name = “LoveHandles”;
chickenpox.setSeconds(75);


These statements create a new Virusobject called chickenpox, set the
namevariable of chickenpox, and then call the setSeconds()method of
chickenpox.

Free download pdf