views:

106

answers:

3

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.

A: 

The constructor is the first function that is run when the class is instantiated into an object.

Class variables are initialized during instantiation, then the constructor is immediately run following that.

Ian
A: 

In most languages, instance fields (they're not called class variables in any language I know of) will be initialized during instance construction. They are effectively part of the constructor, executed before the actual constructor code.

You can certainly initialize them in explicit constructor code (though save yourself the setting to null if you're going to set them to something else).

You asked what a constructor is for - you can't do everything in an initializer. What if you needed to loop or something?

John Saunders
Thanks John for the reply and nice point about having constructors.
Devil Jin
+1  A: 

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:

public class Foo
{
    private var bar:Array = [1, 2, 3];
    private var baz:Array = bar.concat([4, 5, 6]);
}

Doesn't work:

public class Foo
{
    private var baz:Array = bar.concat([4, 5, 6]);
    private var bar:Array = [1, 2, 3];
}
macke