是否有充分的理由使用影子字段的参数?

use*_*645 5 java parameters field shadow

是否有充分的理由使用影子字段的参数?这两者有什么区别:

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

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你this在这个例子中使用没有参数阴影字段的关键字怎么办(我猜它只是不必要的):

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

    //constructor
    public Point(int a, int b) {
        this.x = a;
        this.y = b;
    }
}
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 5

我认为这是一个风格问题,但特别是对于公共领域 - Point(int x,int y)自我记录本身,而Point(int a, int b)不是

  • 即使字段不公开,它们也经常被类的公共API(getter,setter,方法)或类javadoc中描述的对象状态的一部分公开.使用一致的名称确实有帮助 (2认同)