gpt4 book ai didi

java - 了解 "this"在 Java 中的使用

转载 作者:行者123 更新时间:2023-11-29 03:29:06 25 4
gpt4 key购买 nike

我试图理解 java 中的 this 关键字。我想改用 this 关键字重写这段代码。如果我做对了,请告诉我。原代码如下:

public class Book {

private String title;
private String author;
private String publisher;

public Book(String bookTitle, String authorName, String publisherName){
title = bookTitle;
author = authorName;
publisher = publisherName;
}
}

这里是重写的代码:

public class Book {

private String title;
private String author;
private String publisher;

public Book(String title, String author, String publisher){
this.title = title;
this.author = author;
this.publisher = publisher;
}
}

我做对了吗?

谢谢,

凯文

编辑:感谢您的回复...还有一个问题:在修改后的代码的构造函数中,等号的哪一侧是指类变量?例如,在 this.title = title; 中,this.title 是从构造函数还是从类变量引用 title 变量?

根据下面的回复,我认为答案是 this.title 引用了类变量 title

最佳答案

是的。 this 关键字表示“我现在正在运行的此类的实例”。您通常不需要它用于变量或方法引用,但在这种(常见)情况下,构造函数参数与保存它们的字段同名,使用 this 区分字段和参数之间的编译器。

关于java - 了解 "this"在 Java 中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325512/

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