Java 基础知识,使用 this 作为构造函数

标签 java constructor this

我正在自学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 将警告您该方法中未使用参数 citystatecountry。 因此,您可以做的是触发自动修复,其中之一是“分配给新字段”,这将在类中创建字段并在构造函数中分配它们。字段名称将与参数相同,因此需要以 this. 为前缀,以便它们引用字段,而不是参数。

关于Java 基础知识,使用 this 作为构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47795648/

相关文章:

java - 如何获取当年的任何特定日期

c# - 为什么 type.getConstructor 将类型数组作为参数?

C++ 在另一个类中实例化一组具有相同构造函数的类中的类类型变量

javascript - jQuery - 检查这个元素是哪个?

javascript - 无法在此代码中获取 this.value

java - 如何获取一天的开始时间和结束时间?

Java 泛型方法和构造函数

java - MyBatis,插入复杂对象

java - final 字段的初始化顺序

javascript - 如何减少 JavaScript 中内部函数变量的范围?