Reputation: 3
what is an alias in java? Lets say I have a class with three attributes as shown below and a constructor. how would I Array[] x an alias for the parameter named x, the attribute y an alias for the parameter y, and the attribute z an alias for the parameter z.
public class Apples
{
private Array[] x;
private String y;
private String z;
public Apples(String y, String z, Array[] x)
{
}
}
Upvotes: 0
Views: 932
Reputation: 201447
x
, y
and z
are variable shadows (or aliases) in the Apples
constructor. And you can use this
to resolve it. Like
private Array[] x; // <-- attribute named x
private String y; // <-- attribute named y
private String z; // <-- attribute named z
public Apples(String y, // <-- parameter named y
String z, // <-- parameter named z
Array[] x) // <-- parameter named x
{
this.y = y; /* assign parameter y to this instance attribute named y */
this.z = z; /* assign parameter z to this instance attribute named z */
this.x = x; /* assign parameter x to this instance attribute named x */
}
If your constructor omitted this
like
public Apples(String y, String z, Array[] x) {
y = y;
z = z;
x = x;
}
You would assign the values back to the parameters (essentially a no-op) because they alias the attributes (and the instance fields would be null
).
Upvotes: 1