let me illustrate one more example which may make the concept of "this" clear to
u.
Let's take the following peice of code:
public void addFirst)(Object item)
{
head = new ListNode(item,node);
++size;
}
ListNode(Object data ,ListNode next)
{
this.data = data;
this.next = next;
}
Notice here that we have a simple bit of a program that creates a linked list.
What u see in the constructor ListNode is interesting.\
Let's go back to the following line of code:
head = new ListNode(item,node);
which has item and node as parameters. Actually these are references and are
REFERENCE VARIABLES in java.
These are passed to Object data ,ListNode next - the intermediate reference
variables that take on the references from the item and node respectivelly
Now let us go back to the Class ListNode which is as follows:
class ListNode{
Object data;
List Node next;
ListNode(Object data ,ListNode next)
{
this.data = data;
this.next = next;
}
which is the same i wrote earlier
.Now notice that the INSTANCE VARIABLES DECLARED IN THE class ListNode are
Object data and ListNode next.
These are similar in names to the reference variable, which u will readily
agree.
Now to distinguish between these 2 we have to write statements like
this.data = data;
//here this.data refers to Instance variable "data" declared in ListNode and
this.next agains refers to instance variable "next" declared in ListNode
Since we are passing the reference from reference variables "data" and "next" to
Instance Variables "data" and "next" the distinguishing syntax is necessary to
avoid getting the compiler to give u error messages and getting confused
So are u with me upto this? If u have any doubts mail me again and i will be
glad to try to sort out any question u may have.