java中的别名是什么?假设我有一个具有三个属性的类,如下所示和一个构造函数。如何将Array [] x作为名为x的参数的别名,属性y作为参数y的别名,属性z作为参数z的别名。
public class Apples
{
private Array[] x;
private String y;
private String z;
public Apples(String y, String z, Array[] x)
{
}
}
答案 0 :(得分:1)
x
,y
和z
在 Apples
构造函数中是variable shadows(或别名)。您可以使用this
来解决它。像
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 */
}
如果您的构造函数省略 this
,则
public Apples(String y, String z, Array[] x) {
y = y;
z = z;
x = x;
}
您可以将值分配回参数(基本上是无操作),因为它们别名属性(实例字段为null
)。