Java Reference
In-Depth Information
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
{
}
The
Student
class declares an instance variable
id
. In its
setId()
method, it also names the parameter
id
, and
uses
this.id
to refer to the instance variable. It also uses
this.id
to refer to the instance variable id in its
getId()
method. Note that there is no name hiding occurring in the
getId()
method and you could use the simple name
id
,
which means the instance variable
id
.
I will discuss the use of the keyword
this
again in this chapter and subsequent chapters. Table
6-2
lists the parts of
a class, the context in which they occur, and the permitted use of the keyword
this
, the instance variable, and the class
variable. I have not yet covered all parts of a class that are listed in Table
6-2
. I will cover them shortly in this chapter.
Table 6-2.
The Context Type and Allowed Use of the Keyword this, an Instance Variable, and a Class Variable
Part of a Class
Context
Can use this
keyword?
Can use instance
variable?
Can use class
variable?
Instance variable initialization
Instance
Yes
Yes
Yes
Class variable initialization
Class
No
No
Yes
Instance initializer
Instance
Yes
Yes
Yes
Class initializer
(Also called static initializer)
Class
No
No
Yes
Constructor
Instance
Yes
Yes
Yes
Instance method
(Also called non-static method)
Instance
Yes
Yes
Yes
Class method
(Also called static method)
Class
No
No
Yes
The keyword
this
is a
final
(a constant is called
final
in Java because Java uses the
final
keyword to declare
a constant) reference to the current instance of the class in which it appears. Because it is
final
, you cannot change
its value. Because
this
is a keyword, you cannot declare a variable named
this
. The following code will generate a
compiler error:
public class ThisError {
void m1() {
// An error. Cannot name a variable this
int this = 10;
// An error. Cannot assign a value to this because it is a constant.
this = null;
}
}