什么时候在Java中使用"this"是合适的

Jam*_*mes 13 java

可能重复:
我什么时候应该在课堂上使用"this"?

在引用实例的字段时,如何知道是否使用"this"?

例如:

return this.name
Run Code Online (Sandbox Code Playgroud)

我被教了一个有用的案例.即当输入参数与字段名称相同时:

public void setName(String name) {
    this.name = name;
}
Run Code Online (Sandbox Code Playgroud)

除此之外,"这个"似乎不需要..还有什么其他案例?

inv*_*ant 6

如果有一个类的构造函数太多,可以使用它来调用其他构造函数.示例:

public class TeleScopePattern {

    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;

    public TeleScopePattern(int servingSize, int servings) {
        this(servingSize, servings, 0);

    }

    public TeleScopePattern(int servingSize, int servings, int calories) {
        this(servingSize, servings, calories, 0);

    }

    public TeleScopePattern(int servingSize, int servings, int calories, int fat) {

        this.servingSize = servingSize;
        this.servings = servings;
        this.calories = calories;
        this.fat = fat;

    }

}
Run Code Online (Sandbox Code Playgroud)


Rom*_*man 5

在少数情况下你必须使用它:

  1. 如果您具有相同的字段名称和方法参数/局部变量,并且您想要读/写该字段

  2. 当您想要从内部类访问外部类的字段时:

    class Outer {
    
        private String foo;
    
        class Inner {
            public void bar() {
                 System.out.println(Outer.this.foo);
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 当你想从另一个构建函数中调用一个构造函数时(但它更像是一个方法调用 - this(arg1, arg2);

所有其他用法只是一种风格问题.