理解“this"的用法在 Java 中 [英] Understanding use of "this" in java

查看:33
本文介绍了理解“this"的用法在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆