ren.rocks
ren.rocks

Reputation: 792

Can you use the "this." keyword to reference an array?

For example:

If you are writing a class constructor and decide that you want to pass an array, could you make use of the "this keyword to reference that array?

private int[] a;
private int size;   

public Play(int[] a, int size)
{
this.a = a;
this.size = size;
}

My initial guess is no, because it would act similar to c++ where you can't just clone data into an array. Please help me understand it.

Upvotes: 0

Views: 8063

Answers (4)

PM 77-1
PM 77-1

Reputation: 13334

Yes, you can. One reference variable will be assigned a value of another reference variable. Object that they point to does not change and no new objects are constructed.

So it will not clone anything.

Upvotes: 1

Debojit Saikia
Debojit Saikia

Reputation: 10632

When you use this.a, it refers to the instance variable a. As in the same scope there are two a's now, this.a will refer to the instance variable and a would refer to the local variable that was passed as parameter.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

From the java language specification

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.

The type of this is the class C within which the keyword this occurs.

So when you use this in your constructor, it is a reference to the Play object you are constructing. When you do this.someMember, you are dereferencing the reference stored in this to access the member someMember on the object. It doesn't matter that that member is an array.

Upvotes: 3

coletrain
coletrain

Reputation: 2849

You only need to use this when another variable within the current scope shares the same name and you want to reference to the instance. Theres no difference between a and this.a

Upvotes: 1

Related Questions