On 22 November 2010 16:53, Craig Kelley <[email protected]> wrote:
> Hello Java Posse.
>
> In a break from Oracle and Google legal fun, I thought I'd throw this
> problem out there. We're running into a strange, what seems to be JVM-
> related issue. Given the following classes:
>
> abstract class Inner {
> Inner() { run(); }
> public abstract void run();
> }
>
> public class Outer {
> public static void test(final String s) {
> Inner i = new Inner() {
> public void run() {
> System.out.println("s = " + s);
> }
> };
> i.run();
> }
>
> public static void main(String[] args) {
> test("hello");
> }
> }
>
> Why does jre 1.4 return this:
>
> s = null
> s = hello
>
> But jre 6 returns this:
>
> s = hello
> s = hello
>
as Ricky said, the superclass' constructor is called before the subclass'
... which means it happens before field initialization in the subclass
you can see a similar effect in the following non-inner example:
static abstract class A {
public A() {
run();
}
public abstract void run();
}
static class B extends A {
String s;
public B( String s ) {
// A's constructor called --> run();
this.s = s;
}
@Override
public void run() {
System.out.println( s );
}
public static void main( String[] args ) {
new B( "hello" ).run();
}
}
the difference between 1.4 and 6 in your example is therefore probably due
to some difference in how it initializes the implicit reference to the outer
final variable
anyway regardless of the actual cause, I'd offer the same advice as Ricky:
avoid calling overridable methods from constructors
We have an application targeting jre6 that is getting null pointer
> exceptions from variables supposedly declared final, referenced from
> inner classes.
>
--
Cheers, Stuart
--
You received this message because you are subscribed to the Google Groups "The
Java Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.