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:
Yes it's fine, mainly because, syntactically , they're used differently.
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.
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.
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()) {
}
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