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.