Wednesday, 15 January 2014

java - Variable is null at super call -



java - Variable is null at super call -

i'm using java 7 , got 3 classes:

testsuper.java

public abstract class testsuper { public testsuper() { testmethod(); } protected abstract void testmethod(); }

testnull.java

public class testnull extends testsuper { private string test = "test"; public testnull() { super(); system.out.println(test); } @override protected void testmethod() { system.out.println(test); } }

testmain.java

public class testmain { public static void main(string[] args) { new testnull(); } }

output:

null test

why happen , there workaround it?

when phone call new testnull(); you're calling constructor of class testnull, calls super() constructor: contains phone call method implemented in testnull, print string field, @ time fields of sub-class testnull not yet initialized, i.e. null.

after super constructor call, fields initialized, , hence sec print show new value of (initialized) string.

the key point here fields of sub-class initialized after instantiation of super-classes.

a workaround? depends on exact behaviour desire: maybe makes sense not phone call abstract method in super constructor (i.e. in constructor of testsuper class).

java nullpointerexception null superclass super

No comments:

Post a Comment