Re-declaring variables with access modifiers in Java

If I declare a variable private, can I re-declare it in another way?

This is the key because I used Netbeans to generate my GUI code, and it uses the same names for variables every time. Is there a way to avoid changing each variable?

ADDITIONAL / EDITING: Does this also apply to the methods themselves? What about objects?

+4
source share
4 answers

Local variables inside a method cannot be declared using visibility modifiers ( public , private , protected or by default), only class attributes can use these modifiers.

You can reuse the same variable names for different methods, this will not cause conflicts. It is good practice to define local variables in a method with different names from class attributes. To make sure:

 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 ok to reuse local variable names String localVariable2; // but you shouldn't name them attribute1 // or attribute2, like the attributes } } 
+2
source

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

+3
source

This is permissible if this is what you are talking about:

 public class Experiment { private int test; public void again() { int test ; //the local variable hides the previous one } } 
+2
source

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" } } 

A variable outside the method is obscured by a variable with the same name inside the method. Such a thing is discouraged because it is easy to confuse. Here you can read here and here .

+1
source

Source: https://habr.com/ru/post/1390075/


All Articles