有人能详细解释一下

有人能详细解释一下

本文介绍了有人能详细解释一下“这个”的用法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白在Java中使用'this'。如果有人可以帮我澄清,我会非常感激。

I don't really understand the use of 'this' in Java. If someone could help me clarify I would really appreciate it.

在这个网站上它说:

在实例方法或构造函数中,这是对当前对象的引用 - 正在调用其方法或构造函数的对象。您可以在实例方法中引用当前对象的任何成员或一个构造函数使用它。

"Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this."

它给出了以下示例:

例如,Point类写得像这样

For example, the Point class was written like this

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

但它可能是这样写的:

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

然而,我仍然不完全理解为什么x = a本来可以写成this.x = x?为什么不是这个。=一个?为什么x在左侧?

Yet, I still don't fully understand why x = a could have been written as this.x = x? Why isn't it this.x = a? Why is the x on the left side?

对不起,我对Java很新。我为无聊的专家道歉。

I'm sorry but I am very new to Java. I apologize for boring the experts.

推荐答案

如果定义了一个与对象属性同名的变量/参数,它会重叠该属性的名称和一个应该使用this.var_name。

If some variable/argument with same name as object's property is defined, it "overlaps" the name of that property and one should use this.var_name.

所以是的,它可以写成 this.x = a ,但有点多余。

So yes, it could be written as this.x = a, but is somewhat redundant.

这篇关于有人能详细解释一下“这个”的用法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:11