java - When Initializing object, instance variable not initialized always? -
the following code produces nullpointerexception -
public class myclass { static myclass instance= new myclass(); // line 3 static boolean have_instance = true; boolean inst_avail=have_instance; // line 5 boolean isinstavail(){ return inst_avail; } public static void main(string[] args) { system.out.println(instance.isinstavail() ? "instance there.":""); // gives java.lang.nullpointerexception } }
if move line 3
after line 5
, runs fine. how order matter here? shouldn't instantiation of class set ivar values everytime?
when object created on line 3 class has not finished initializing yet, , have_instance
variable has default value, null
. value assigned inst_avail
member variable of object, value returned instance.isinstavail()
in main
method null
.
an easy way fix swapping lines 3 , 4, have_instance
has value when object created. or declare have_instance
boolean
instead of boolean
, have value false
, not null
. make program print nothing though.
or maybe rethink you're trying do. it's idea create instances of class before class has finished initializing, if class not "final" (i.e. may have subclasses).
Comments
Post a Comment