且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用“这个"?在一个班级?

更新时间:2022-12-08 10:29:55

this 关键字主要用于三种情况.第一个也是最常见的是在 setter 方法中消除变量引用的歧义.第二种是需要将当前类实例作为参数传递给另一个对象的方法时.第三种是作为从构造函数内部调用备用构造函数的一种方式.

The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.

案例 1: 使用 this 来消除变量引用的歧义.在 Java setter 方法中,我们通常传入一个与我们试图设置的私有成员变量同名的参数.然后我们将参数 x 分配给 this.x.这清楚地表明您正在将参数name"的值分配给实例变量name".

Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

public class Foo
{
    private String name;

    public void setName(String name) {
        this.name = name;
    }
}

案例 2: 使用 this 作为传递给另一个对象的参数.

Case 2: Using this as an argument passed to another object.

public class Foo
{
    public String useBarMethod() {
        Bar theBar = new Bar();
        return theBar.barMethod(this);
    }

    public String getName() {
        return "Foo";
    }
}

public class Bar
{
    public void barMethod(Foo obj) {
        obj.getName();
    }
}

案例 3: 使用 this 调用备用构造函数.在评论中,trinithis正确地指出了this的另一个常见用法>.当一个类有多个构造函数时,你可以使用 this(arg0, arg1, ...) 来调用你选择的另一个构造函数,前提是你在构造函数的第一行这样做.

Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.

class Foo
{
    public Foo() {
        this("Some default value for bar");

        //optional other lines
    }

    public Foo(String bar) {
        // Do something with bar
    }
}

我还看到 this 用来强调实例变量被引用的事实(不需要消除歧义),但在我看来这是一种罕见的情况.

I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.