Java Reference
In-Depth Information
// Set a new value
out.setValue(828);
// Print the value
out.printValue();
in.printValue();
}
}
Outer: Value = 1116
Inner: Value = 1720
Outer: Value = 828
Inner: Value = 1720
Note that the output has changed. When printing the value for the first time, the
Outer2
class's instance prints 1116,
whereas the
Inner2
class's instance prints 1720. After you set the new value using
out.setValue(828)
, the
Outer2
class's
instance prints the new value of 828, whereas
Inner2
class's instance still prints 1720. Why does the output differ?
To fully understand the above output, you need to understand the concept of the current instance and the
keyword
this
. So far, you understand that the keyword
this
refers to the current instance of the class. For example,
inside the
setValue()
instance method of the
Outer2
class,
this.value
refers to the
value
field of the current
instance of the
Outer
class.
You need to revise the meaning of the keyword
this
with respect to the instance of a class. The meaning of the
keyword
this
that it refers to the current instance is sufficient as long as you deal with only instances of top-level
classes. In dealing with only top-level classes, there is only one current instance in context when a piece of code is
executed. In such cases, you can use the keyword
this
to qualify the instance member names to refer to the instance
members of the class. You can also qualify the keyword
this
with the class name to refer to the instance of the class in
context. For example, inside the
setValue()
method of the
Outer2
class, instead of writing
this.value
, you can also
write
Outer2.this.value
. If the name of a variable used inside a class in a non-static context is an instance variable
name, the use of the keyword
this
is implicit. That is, the use of the simple name of a variable inside a class in a
non-static context refers to the instance variable of that class unless that variable hides the name of an instance
variable with the same name in its superclass. The use of the keyword
this
alone and its use qualified with class name
is illustrated in Listing 2-17. The program in Listing 2-18 tests the uses of the keyword
this
concept.
Listing 2-17.
Use of the Keyword this Qualified with the Class Name
// QualifiedThis.java
package com.jdojo.innerclasses;
public class QualifiedThis {
// Instance variable - value
private int value = 828;
public void printValue() {
// Print value using simple name of instance variable
System.out.println("value=" + value);
// Print value using keyword this
System.out.println("this.value=" + this.value);
// Print value using keyword this qualified with the class name
System.out.println("QualifiedThis.this.value=" + QualifiedThis.this.value);
}