Constructor and Initialization

  • Thread starter Thread starter Yehia A.Salam
  • Start date Start date
Y

Yehia A.Salam

Hello,

this is a little too basic but what's the difference between writing my code
in the initialization section and in the constructor section, I know that
the initialization parts gets executed first, but is there any other
differences :


public class Test: Control {

VScrollBar v;
v = new VScrollBar(); ??

Test(){
v = new VScrollBar(); ??
}

}

Thanks
Yehia
 
Hello, Yehia!

AFAIK no.

There are only limitations with initialization approach.
e.g. there is no equivalent for:

//ctor
Test()
{
//do some specific calculations/actions
v = new VScrollBar();
}



YA> this is a little too basic but what's the difference between writing
YA> my code
YA> in the initialization section and in the constructor section, I know
YA> that
YA> the initialization parts gets executed first, but is there any other
YA> differences :


YA> public class Test: Control {

YA> VScrollBar v;
YA> v = new VScrollBar(); ??

YA> Test(){
YA> v = new VScrollBar(); ??
YA> }

YA> }

YA> Thanks
YA> Yehia



--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 
Use the constructor to initialize values that an instance of the class will
use. Create fields and intialize those according to whether or not they are
use internally by the class or externally in an instance.


So, I would prefer:

public class Test: Control {

VScrollBar v;

Test(){
v = new VScrollBar();
}
}

over this:

public class Test: Control {

VScrollBar v;
v = new VScrollBar();

Test(){

}
}

Whe "v" is used in the instance, but the other way around when "v" is used
internally by the class code only.
 
Scott M. said:
Use the constructor to initialize values that an instance of the class will
use. Create fields and intialize those according to whether or not they are
use internally by the class or externally in an instance.


So, I would prefer:

public class Test: Control {

VScrollBar v;

Test(){
v = new VScrollBar();
}
}

over this:

public class Test: Control {

VScrollBar v;
v = new VScrollBar();

Test(){

}
}

I'd prefer the former too - but mainly because it will compile, whereas
the latter won't!
 
Back
Top