简体   繁体   中英

Is it ok to name the variables the same name on different methods?

i am new to java and i have a question. lets say i have this code:

public class Number {
    private int[][] number;
    private int row;
    private int column;

    public Number(int[][] num) {
        this.row = num.length;
        this.column = num[0].length;
        this.number = new int[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                number[i][j] = num[i][j];
            }
        }
    }

    public Number(int row, int column) {
        this.row = row;
        this.column = column;
        number = new int[row][column];
    }

    public Number getNewNumber() {
        Number newNumber = new Number(row, column);
        for (int i = 0; i < row; i++) {
            newNumber.number[i] = number[i];
        }
        return newNumber;
    }

    public int getNewNumberSum() {
        Number newNumber = new Number(row, column);
        int sum = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                newNumber.number[i][j] = number[i][j];
                sum += newNumber.number[i][j];
            }
        }
        return sum;
    }
}

My question is about the syntax. is it ok to name the object's name the same on a different method and variables names the same on different methods?

Thank you

In a word, yes. Variable names only hold in the scope they're defined in, and you can use the same name in different scopes.

Since they are method local variables and you can access them only inside that method, there won't be any issues. So it is ok to have variables with same name in different methods as long as they are method local.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM