See the two ways of class definition:
//definition: 1 public class MyClass{ private MyObject obj = new MyObject(); private String str = 'hello world'; // constructor public MyClass(){ } } // definition: 2 public class MyClass{ private MyObject obj = null; private String str = null; // constructor public MyClass(){ obj = new MyClass(); str = 'HelloWorld'; } }
My question is: when are the class variables loaded. How are they loaded?
How does their initialization happen? If their initialization can happen as in definition 1, what is the purpose of a constructor?
Which is the preferred way of defining the class and why? Is the behavior same across C++/C#/Java or this behavior differs across them?
Any clarification comment on the above is welcome.
This depends on the language, but most languages initialize fields before calling the constructor. Generally I advocate doing things in context, initialization is usually only relevant where the fields are declared. However, as John pointed out, sometimes you need to do something which doesn’t make sense/is possible in one line.
Also, as always, order is important if you have fields that depend on other fields for their initialization. In some languages, like ActionScript, this means the order of the declarations determine the order of initialization:
Works:
Doesn’t work: