成员变量和局部方法变量可以同名吗?[英] Can member variable and local method variable have the same name?

问题描述

我将如何做到这一点?

class Test {
    private int var1;

    public Test(int var1) {
        var1 = var1; //set the member variable to what was passed in
    }
}

我确信有一个非常明显的答案.它现在只是在逃避我.

推荐答案

是的,他们可以同名.但是,要引用实例变量,您需要使用 this 前缀:

public Test(int var1) {
    this.var1 = var1;
}

本文地址:https://www.itbaoku.cn/post/978796.html