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?
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With