Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading data in constructors and not in constructors

I just want to know the difference between loading the data inside the constructor and loading the data outside the constructor but not inside any methods

example: Loading inside constructor

public class Model{
   Object testobject;

   public Model(){
      testobject=new Object();
   }

}

VS

example: Loading outside constructor

public class Model{
   Object testobject=new Object();

   public Model(){
   }

}
like image 965
Richeve Bebedor Avatar asked Jan 22 '26 04:01

Richeve Bebedor


1 Answers

The only difference is when you have multiple constructors it can be tedious to write...

testObject = new Object();

in every single one. However if you decided you want...

public Model(Object otherObject) {
    testObject = otherObject;
}

You would be doing slightly more work if you declared it twice.

like image 81
Pace Avatar answered Jan 25 '26 08:01

Pace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!