Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-declaring Variables with Access Modifiers in Java

If I declare a variable to be private, am I able to re-declare it in another method?

This is key because I used Netbeans to generate my GUI code, and it uses the same names for variables every time. Is there any way that I can avoid having to change every variable?

ADDITION/EDIT: Does this also apply for the methods themselves? How about objects?

like image 832
fr00ty_l00ps Avatar asked Feb 22 '23 21:02

fr00ty_l00ps


2 Answers

A local variable and a private instance variable, even with the same name, are two different variables. This is allowed. The local variable hides the instance variable. The only way to access a hidden instance variable is to prefix it with this.

like image 167
JB Nizet Avatar answered Mar 08 '23 15:03

JB Nizet


The local variables inside a method can not be declared with visibility modifiers (public, private, protected or default), only the attributes of a class can use those modifiers.

You can reuse the same variable names across different methods, it won't cause conflicts. It's a good practice to name the local variables in a method with different names from those of the attributes of the class. To make myself clear:

public class Test {

    private String attribute1; // these are the attributes
    private String attribute2;

    public void method1() {
        String localVariable1; // variables local to method1
        String localVariable2;
    }

    public void method2() {
        String localVariable1; // it's ok to reuse local variable names
        String localVariable2; // but you shouldn't name them attribute1
                               // or attribute2, like the attributes
    }

}
like image 33
Óscar López Avatar answered Mar 08 '23 16:03

Óscar López