您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 24

Keyword 'this'

When an object wishes to send itself a message to invoke one of its own methods, it is not necessary to use the dot notation.

Consider an object that is an instance of the class Customer. A method of a instance of this class might be invoked from the statement:

oldBalance = m1();
This statement means send the message m1() to itself, to result in its corresponding m1() method being invoked.

In the absence of the dot notation Java assumes that a message is to be send to the sending object itself. 

Java actually provides a keyword to mean 'the object sending the message'. The keyword is:

this
So we could replace the line above, with the following:
oldBalance = this.m1();
and the result would be the same. We have simply made it explicit that the message is to be sent to the object itself.

In fact, when Java spots that no object (or class) has been specified to receive a message, it inserts the sending object itself to be the recipient of the message (i.e. Java will automatically insert the this. so that it know where every message is to be sent).

The this keyword is also useful when an object wishes to send a reference to itself as part of a message or reply ?in such a situation this is passed as a message argument or a return value.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg