Re: Is this specified somewhere?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




On 14-Oct-09, at 6:22 AM, Christoph Höger wrote:

Hi,

I was just pointed to a strange thing in javas anonymous class features.

Consider the following class:

package javabug;

public class NormalTestClass {

	final Integer i; //mark

	NormalTestClass() {
		i = 101; //mark
		foo();
	}

	public void foo() {	}
}


When you create an anonyous class like

final Integer i = 100;

		NormalTestClass myClass = new NormalTestClass() {
			
			@Override
			public void foo() {
				System.err.println(i);
			}	
		};

Instead of 100 the output would be 101.
The problem is that we had discussed a case that used to occur in older versions of java when you removed the marked lines: In that case in the
first call of foo() the variable i would not yet be initialised and
therefore be null.
This is fixed now. But what you get now is problematic on its own:
Effectively you are forced into not using variables that are privately
used by the superclass (you might not even know of).

Any comments on this issue?


Actually, it makes perfect sense.

The first i is package scoped, not private, so it is visible to the child class if it's in the same package, and the second i is at a higher scope level than the anonymous class. Inside the anonymous class definition, you're referencing the 'closest' scoped variable with that name, which is the class variable rather than what it might view as a global variable. If you moved the definition of the 100 inside the anonymous class, then your new foo() would reference it.

Aaron
--
"In the last, lorn fight
'gainst the fall of long night,
the mountains stand guard,
and the dead shall be ward,
for the grave is no bar to my call."
--The Horn Of Valere



--
fedora-devel-java-list mailing list
fedora-devel-java-list@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/fedora-devel-java-list

[Index of Archives]     [Red Users]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [KDE Users]

  Powered by Linux