fr00ty_l00ps
fr00ty_l00ps

Reputation: 730

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?

Upvotes: 4

Views: 500

Answers (4)

cyber-monk
cyber-monk

Reputation: 5570

Consider the following

public class Example {

  private String outerString = "outer";

  public void exampleMethod(){
    String outerString = "inner";
    System.out.println(outerString);      // prints "inner"
    System.out.println(this.outerString); // prints "outer"
  }
}

The variable outside the method is shadowed by the variable with the same name within the method. This kind of thing is discouraged because it's easy to get confused. You can read more here and here.

Upvotes: 1

Óscar López
Óscar López

Reputation: 236104

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
    }

}

Upvotes: 2

COD3BOY
COD3BOY

Reputation: 12112

This is valid, if this is what you are referring to :

public class Experiment {

    private int test;

      public void again()
        {
            int test ;   //the local variable hides the previous one
        }

}

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691933

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.

Upvotes: 3

Related Questions