class - Order of initialization of data fields in java -
in code below, order of initialization of data fields? general rule followed java data member , member functions?
public class testclass { int j=10; static int h=5; public static void main(string[] args) { testclass obj= new testclass(); } }
in general:
1) static field members (static initializers in general)
2) non-static field members
3) constructor
however can test snippet of code this:
public class testclass { int = 10; static int j = 20; public testclass() { // todo auto-generated constructor stub system.out.println(i); = 20; system.out.println(i); } public static void main(string[] args) { new testclass(); } }
quoting great "thinking in java":
within class, order of initialization determined order variables defined within class. variable definitions may scattered throughout , in between method definitions, variables initialized before methods can called—even constructor. ................................... there’s single piece of storage static, regardless of how many objects created. can’t apply statickeyword local variables, applies fields. if field staticprimitive , don’t initialize it, gets standard initial value type. if it’s reference object, default initialization value null.
to summarize process of creatingan object, consider class called dog:
even though doesn't explicitly use static keyword, constructor static method. first time object of type dog created, or first time static method or static field of class dog accessed, java interpreter must locate dog.class, searching through class path.
as dog.class loaded (creating class object, you’ll learn later), of static initializers run. thus, static initialization takes place once, class object loaded first time.
when create new dog( ), construction process dog object first allocates enough storage dog object on heap.
this storage wiped zero, automatically setting primitives in dog object default values (zero numbers , equivalent boolean , char) , references null.
any initializations occur @ point of field definition executed.
constructors executed.this might involve fair amount of activity, when inheritance involved.
Comments
Post a Comment