gpt4 book ai didi

java - 为什么在 Constructor 和 Setters 中使用 "this"关键字?

转载 作者:搜寻专家 更新时间:2023-11-01 04:07:21 25 4
gpt4 key购买 nike

构造函数用于在创建类实例时初始化一个值并将其分配给类变量,对吧?

public class Joke{
private String jokeSetup;
private String jokePunchLine;

public Joke(String jokeSetup , String jokePunchLine){
this.jokeSetup=jokeSetup;
this.jokePunchLine=jokePunchLine;
}
}

考虑以下几点:

public Joke(String jokeSetup , String jokePunchLine) 

是否创建了另一个同名变量?

如果是这样,为什么将它们分配给以前的 jokeSetupjokePunchLine 值?

PS:这段代码不是我写的,在我学习Java的视频中有展示。

最佳答案

构造函数的目的是初始化刚刚创建的对象,例如通过填充其实例字段(也称为实例变量)。 this 在您的构造函数中用于引用构造函数正在初始化的实例。

在您的示例构造函数中,您有参数实例字段。构造函数获取参数值并将这些值分配给实例字段:

public Joke(String jokeSetup , String jokePunchLine)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---- Declares parameters this
// constructor accepts when
// called
{
// vvvvvvvvv------------ parameter
this.jokeSetup=jokeSetup;
// ^^^^^^^^^^^^^^---------------------- instance field

// vvvvvvvvvvvvv---- parameter
this.jokePunchLine=jokePunchLine;
// ^^^^^^^^^^^^^^^^^^------------------ instance field
}

构造函数可以改为使用常量值初始化实例字段,或者通过间接使用参数值(例如,查找某些东西)等。它并不总是像您的示例中那样直接一对一赋值。

在您的示例中,参数与实例字段同名,但这不是必需的。例如,此构造函数与您的构造函数完全相同:

public Joke(String theJokeSetup , String theJokePunchLine)
// ^---------------------^---------- Note the name changes
{
// vvvvvvvvvvvv------------ parameter
this.jokeSetup = theJokeSetup;
// ^^^^^^^^^^^^^^--------------------------- instance field

// vvvvvvvvvvvvvvvv---- parameter
this.jokePunchLine = theJokePunchLine;
// ^^^^^^^^^^^^^^^^^^----------------------- instance field
}

Java 允许您在引用实例字段时省略 this. 部分,只使用字段名称本身(例如 jokeSetup 而不是 this .jokeSetup).但是,除非重命名参数,否则不能在构造函数中执行此操作,因为它们与实例字段具有相同的名称,因此构造函数中的 jokeSetup 是参数,而不是字段。当存在这样的冲突时,最本地标识符优先(在您的构造函数中,参数是最本地的)。

当没有冲突时,是否使用 this. 部分是风格问题。 (我总是使用 this.,我发现它更清晰。)因此,例如,这是该构造函数的另一个版本,它与您的原始构造函数完全相同:

public Joke(String theJokeSetup , String theJokePunchLine)
// ^---------------------^---------- Note the name changes
{
// vvvvvvvvvvvv------------ parameter
jokeSetup = theJokeSetup;
// ^^^^^^^^^--------------------------- instance field

// vvvvvvvvvvvvvvvv---- parameter
jokePunchLine = theJokePunchLine;
// ^^^^^^^^^^^^^----------------------- instance field
}

我提到这个是因为,再一次,当没有冲突时,这是一个风格问题,你会看到有时会使用这种风格。

关于java - 为什么在 Constructor 和 Setters 中使用 "this"关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50225277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com