想知道这两者有没有区别:
public Bee (double weight)
{
this.weight = weight;
和
public Bee (double weight)
{
weight = this.weight;
如果您切换等号“=”的左侧和右侧,它会改变含义吗?
是的。意义肯定会改变。一个分配weight
to的值this.weight
,另一个分配this.weight
to的值weight
。
后者将分配存储在您的类weight
字段中的值并将其分配给weight
传递给您的方法的参数。
前者会适得其反。
基本上,this.weight
指的是您的类的weight
字段,其中weight
指的是方法的参数。如果方法范围内没有weight
变量,您仍然可以使用weight
来引用类字段。
是的。关键字表示该this
变量是类实例变量。如果没有this
关键字,将使用本地权重参数。
下面的示例将传递给构造函数的参数分配给同名的类实例变量。
示例类:
public class Bee
{
double weight;
public Bee(double weight)
{
this.weight = weight;
}
}
是的。它们不一样。 this.weight
指的是类上的属性或变量,weight
指的是方法中的参数。
举个例子:
public class Bee
{
private double weight;
public Bee (double weight)
{
this.weight = weight;
}
}
如果我想改变函数中的参数权重,我可以这样做:
public class Bee
{
private double weight;
public Bee (double initialWeight)
{
this.weight = initialWeight;
}
}
如果我想改变内部变量权重,我会这样做:
public class Bee
{
private double internalWeight;
public Bee (double weight)
{
this.internalWeight = weight;
}
}
正如您所看到的,任何一种更改都可以使这里发生的事情更加清晰,它还可以帮助您了解每次调用的设置。