在Java中访问类内部实例变量的最佳方法是什么?

You*_*mon 1 java oop instance-variables this

我刚开始学习Java ,它很棒.有一件事我需要理解,在类中我们可以通过两种方式访问​​实例变量:

class Box {

    // Instance variables
    private int width;
    private int height;
    private int depth;

    // First way
    public void set_volume(int a, int b, int c) {
        this.width = a;
        this.height = b;
        this.depth = c;
    }

    // Second way
    public void set_volume_v2(int a, int b, int c) {
        width = a;
        height = b;
        depth = c;
    }

}
Run Code Online (Sandbox Code Playgroud)

在这里,Instance变量可以在没有this关键字的情况下访问.那么最好的方法是什么?或者它们之间有什么区别?

Men*_*ena 5

如果this它们共享相同的名称,则允许您确保引用实例变量而不是参数.

这通常被认为是实例方法和构造函数中的最佳实践.

否则你的两种方法是等价的.