理解“this"的用法在 Java 中

编程入门 行业动态 更新时间:2024-10-27 10:32:30
本文介绍了理解“this"的用法在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试理解 java 中的 this 关键字.我想改用 this 关键字来重写这段代码.如果我做得对,请告诉我.这是原始代码:

I'm trying to understand the this keyword in java. I wanted to rewrite this code by using the this keyword instead. Please let me know if I've done it right. Here's the original code:

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变量?

Thanks for the responses... one more question: in the constructor of the revised code, which side of the equals sign refers to the class variables? For example, in this.title = title;, does this.title refer to the title variable from the constructor or from the class variable?

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

Based on the responses below, I think the answer is this.title refers to the class variable title.

推荐答案

是的.this 关键字的意思是我现在在里面运行的这个类的实例".您通常不需要它用于变量或方法引用,但在这种(常见)情况下,构造函数参数与保存它们的字段具有相同的名称,使用 this 区分字段和参数之间的编译器.

Yes. The this keyword means "the instance of this class that I'm running inside right now". You usually don't need it for variable or method references, but in this (common) case where the constructor parameters have the same name as the fields they're being saved in, using this distinguishes to the compiler between the fields and the parameters.

这篇关于理解“this"的用法在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 16:41:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:quot   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!