我正在自学Java。我读了这段代码,我需要解释。
为什么在这段代码中(复制自https://www.javatpoint.com/aggregation-in-java)this
已经用过?
这不就等于方法里有不同的局部变量名如:
public Address(String i, String j, String k)
只需使用 city=i
反而?
使用this.city=city
有理由吗?这里?
谢谢。
public class Address {
String city,state,country;
public Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
事实上,我会将代码编写为:
public class Address
{
String city,state,country;
public Address(String tempCity, String tempState, String tempCountry) {
mycity = tempCity;
state = tempState;
country = tempCountry;
}
}
与第一个版本相比,第二个版本有哪些优点和缺点?
最佳答案
至于为什么这实际上很常见:IDE 提供自动分配。例如,您在 Eclipse 中所做的就是输入
class Address {
public Address(String city, String state, String country) {}
}
Eclipse 将警告您该方法中未使用参数 city
、state
和 country
。
因此,您可以做的是触发自动修复,其中之一是“分配给新字段”,这将在类中创建字段并在构造函数中分配它们。字段名称将与参数相同,因此需要以 this.
为前缀,以便它们引用字段,而不是参数。
关于Java 基础知识,使用 this 作为构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47795648/