Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach with variable name equal to field name

Tags:

Found interesting thing while compile the following piece of code:

1    class A {
2        
3     private B line;
4   
5     public void foo() {
6       for (Integer line : line.getElements()) {
7    
8       }
9     }
10    }
11    
12    class B {
13    
14      List<Integer> getElements() {
15         return null; // doesn't matter
16      }
17    }

Pay attention to line 6: we see that variable name is equal to field name. IntelliJ Idea 11 ignores this and think there is no trouble here. But java compiler tells me that 'line doesn't have method getElements'. So, two questions:

  1. Should I submit a bugreport in Idea?
  2. Why the error message from Java is like this? Isn't it able to detect the mistake? What mechanism is working here? Eclipsing of field variable?
like image 949
Vladimir Ivanov Avatar asked Jan 29 '12 08:01

Vladimir Ivanov


People also ask

Can method name and variable name be same?

Yes it's fine, mainly because, syntactically , they're used differently.

Can you declare two variables with the same type and name?

Although it is usually a bad idea, you can declare a formal parameter or a local variable with the same name as one of the instance variables.


2 Answers

This may be a bug in the Java compiler you are using. According to the Java Language Specification (section 14.14.2), the scope of the variable in an enhanced for statement is the contained statement. (This seems to exclude the iterable or array expression to the right of the :.)

You can work around the problem by using this.line.getElements().

EDIT Just for kicks, I submitted this as a bug report to Sun. We'll see whether the Java engineers think it's a bug in the JLS or in javac (or if they have some other explanation). The bug id is 7139681, although it won't be posted to the external database for a couple of days.

like image 190
Ted Hopp Avatar answered Oct 13 '22 03:10

Ted Hopp


If you declare local variable (which is what you have done) with the same name as field, than you can access the field variable as this.name.

for (Integer line : this.line.getElements()) {
}
like image 29
Hurda Avatar answered Oct 13 '22 03:10

Hurda